Jump to content

text columns to arrays?


muppet77

Recommended Posts

i have a file called filename.txt with the csv as below

 

Date,cet,predict,16d

Wed 02/15 @ 12Z,0.7,3.4,x

Wed 02/15 @ 18Z,0.7,3.3,x

Thu 02/16 @ 00Z,0.7,3.3,x

Thu 02/16 @ 06Z,1.1,3.7,x

Thu 02/16 @ 12Z,1.1,3.7,x

 

i would like the date to be replaced by numbers 1,2,3... and to be an array, and also the 2nd value in each row to be an array.

 

the number of rows is not fixed and grows day by day.

 

so the result would be (1,2,3,4,5) and (0.7,0.7,0.7,1.1,1.1).

 

can someone please help?

 

i guessed that some sort of loop is needed to go through row by row, adding values to an array.

 

I have tried the following with no success:

 

// get data from the file
$data = file_get_contents('filename.txt'); 

// use the newline as a delimiter to get different rows
$rows = explode("\n", $data); 
// go through all the rows starting at the second row
// remember that the first row contains the headings
for($i = 1; $i < count($rows); $i++){	
$temp = explode(',', $rows[$i]);	
$date = $temp[0];	
$cet = $temp[1];
$stack = array($stack);
array_push($stack, $cet);}
print_r ($stack);

Link to comment
Share on other sites

sorted , if anyone is interested

 

// get data from the file
$aEntries = file('filename.txt',FILE_IGNORE_NEW_LINES);

// In case you want to keep the header for whatever
$sHeader = array_shift($aEntries);
$iCnt = count($aEntries);
for ($i = 0; $i < $iCnt; ++$i)
{
    $aParts = explode(',', $aEntries[$i]);
    $aResult[$i + 1] = $aParts[1];
}  

$aDates = array_keys($aResult);
$aCet = array_values($aResult);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.