开发者

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开发者_如何学JAVA).

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜