Jump to content

Parsing CSV into associative array


Eamonn

Recommended Posts

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

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

?>

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

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.