简体   繁体   中英

CSV as Associative Array

I have a CSV file I would like to use as an array in a script.

The CSV is simple:

key1,val1
key2,val2
...

I want to be able to reference the array created like this:

$value = my_csv['key'];

I currently cannot do that because my script shows the index as undefined.

$myArray = array();
$file = fopen('myCSV.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  array_push($myArray, array($line[0] => $line[1]));
}
fclose($file);
var_dump($myArray['key']);
exit;

I believe this is because I would need to use the numerical index first but I would ideally be able to reference the array in the way I am above.

The array needs to be created with the key set then, like this

$myArray = array();
$file = fopen('myCSV.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  $myArray[$line[0]] = $line[1];
}
fclose($file);
var_dump($myArray['key']);

This does assume that there are no duplicates in the key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM