Adding a csv column to an array

I have csv with column headers: description, stock, mfgid (and some other headers I don't need).

I need to get data from stock of column headers and mfgid in an array.

I used fgetcsv (), but it put the entire string in an exclusive key in the array.

found this here in stackoverflow, but cannot make it work correctly:

$file = fopen('inventory.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  //$line is an array of the csv elements
  print_r($line);
}
fclose($file);
+3
source share
1 answer

To read in the full CSV file, use this construct:

$csv = array_map("str_getcsv", file("inventory.csv"));
$header = array_shift($csv);

This separates $headerfrom a separate array from the rest of the data $csv.

If you then (seemingly?) Want a map of two fields, try:

$col1 = array_search("stock" $headers);
$col2 = array_search("mfgid", $headers);
foreach ($csv as $row) {
     $map[ $row[$col1] ] = $row[$col2]; }

This will give you an array stockmfgid.

+2
source

All Articles