I am trying to write a csv files with values from two arrays. Here's the code:
<?php
fopen('output.csv','w');
$merged_fields = array_combine($authors, $ids);
$range = count($merged_fields);//gives number of elements in array
$name = array_keys($merged_fields);
$id = array_values($merged_fields);
$name = str_replace(',',', ',$name);
for ($a = 0; $a <=$range; $a++) {
//filter out rows where id = '000000'
if($id[$a] == '000000'){
continue;
}
fputcsv($fp, array_filter(array($name[$a], $id[$a])));
}
}
fclose($fp);
?>
If the original array was "Smith, John" => "888888", "Smith, Jane"=>"777777" , and the next array is "Jones,John"=>"999999" there is a space after the line after each array, so in the csv the output ends up:
"Smith, John",888888
"Smith, Jane",777777
"Johnes, John",999999
I will use this csv to import data and need to get the extra lines out of there. I have tried applying "array_filter" to other parts of the array as it appears there is an empty element in there somewhere, but that hasn't worked.
fputcsvwill end with a new line character as per the docs, so taking that into consideration, it seems to be expected since each loop contains thefputcsvfunction.forloop condition$a <= $rangeshould be$a < $range. Also the variable$ida bit further is undefined. Should it be$empid?"Jones,John"=>"999999"", does that mean you call this piece of code more than once with the intention to add to the file?