muppet77 Posted February 27, 2012 Share Posted February 27, 2012 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); Quote Link to comment https://forums.phpfreaks.com/topic/257878-text-columns-to-arrays/ Share on other sites More sharing options...
Zane Posted February 27, 2012 Share Posted February 27, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/257878-text-columns-to-arrays/#findComment-1321737 Share on other sites More sharing options...
muppet77 Posted February 27, 2012 Author Share Posted February 27, 2012 Thanks Zane. Basically i want row numbers in one array and column 2 data in another array so the result would be (1,2,3,4,5) and (0.7,0.7,0.7,1.1,1.1). Quote Link to comment https://forums.phpfreaks.com/topic/257878-text-columns-to-arrays/#findComment-1321752 Share on other sites More sharing options...
muppet77 Posted February 27, 2012 Author Share Posted February 27, 2012 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); Quote Link to comment https://forums.phpfreaks.com/topic/257878-text-columns-to-arrays/#findComment-1321763 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.