Jump to content

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

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.