Joe
Joe

Reputation: 83

putting csv column into an array

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

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

I was using fgetcsv() but it was putting the entire row into an exclusive key in the array.

found this here at stackoverflow but can't get it to work right:

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

Upvotes: 3

Views: 1435

Answers (1)

mario
mario

Reputation: 145512

For reading in a complete CSV file use this construct:

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

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

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 would give you a stock -> mfgid array.

Upvotes: 2

Related Questions