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
https://forums.phpfreaks.com/topic/257878-text-columns-to-arrays/
Share on other sites

From what you have described.. I have no idea what you want to do.

 

But, I can tell you that instead of a loop for all this, you can use str_getcsv

// get data from the file
$data = file_get_contents('filename.txt'); 
$csv_data = str_csv($data);
// Now $csv_data is an array of it all.

 

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);

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.