3

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);
1
  • 1
    what is the exact problem? what is shown? what's not working? Commented May 3, 2011 at 14:13

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Well it may work for others, but my server is not using php 5.3 so I think that limits me to not being able to use "str_getcsv"
Ah okay. You can try one of the emulations on php.net/manual/en/function.str-getcsv.php#98088 or use upgradephp.berlios.de to get this PHP5.3 function. But you could use your old loop method and just apply the second code block for separating the columns

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.