Eamonn Posted January 16, 2008 Share Posted January 16, 2008 Hey Below is a csv file im trying to insert into a array. operator,55555,1657 operator,66666,3683 operator,77777,9 operator,88888,16066 operator,99999,92 I want to create the array like so. $operator = array(55555 => 1657, 66666 => 3683, 77777 => 9, 88888 => 16066, 99999 => 92); I've used file_get_contents('foobar.csv'); to turn the file into one long string. I think the next stage should be using the explode function with some sort of loop to create the associative array but I'm not sure. I would be grateful for any input. Cheers Link to comment https://forums.phpfreaks.com/topic/86286-parsing-csv-into-associative-array/ Share on other sites More sharing options...
rajivgonsalves Posted January 16, 2008 Share Posted January 16, 2008 try this seeing the structure of your file.. <?php $arrFile = file('foobar.csv'); $arrData = array(); for ($i=0;$i<count($arrFile);$i++) { $arrTemp = explode(",",$arrFile[$i]); $arrData[$arrTemp[1]] = $arrTemp[2]; } print "<PRE>"; print_r($arrData); ?> Link to comment https://forums.phpfreaks.com/topic/86286-parsing-csv-into-associative-array/#findComment-440793 Share on other sites More sharing options...
Eamonn Posted January 16, 2008 Author Share Posted January 16, 2008 perfect... thanks a million Link to comment https://forums.phpfreaks.com/topic/86286-parsing-csv-into-associative-array/#findComment-440846 Share on other sites More sharing options...
kenrbnsn Posted January 16, 2008 Share Posted January 16, 2008 Here's another method, which actually creates the array as the OP wanted: <?php $arrays = array(); // place to store the names of the arrays created $fp = fopen('csv.txt','r'); while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) { if (!in_array($data[0],$arrays)) $arrays[] = $data[0]; // store the name of the array if not already stored ${$data[0]}[$data[1]] = $data[2]; } fclose($fp); foreach($arrays as $ary) { // shows it worked echo '<pre>' . $ary . ' :'; print_r($$ary,true) . '</pre>'; } ?> Ken Link to comment https://forums.phpfreaks.com/topic/86286-parsing-csv-into-associative-array/#findComment-440917 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.