I have this array, and I want to convert it into a CSV file, the problem, is that the array does not generate a csv properly, but just empty fields, why?
Here’s my array contents (the array that I’m printing here is $listaParaCSV
, as the code shown below):
array(2) { [0]=> array(22) { [0]=> string(6) "nombre" [1]=> string(14) "Lun 11-01-2021" [2]=> string(14) "Mie 13-01-2021" [3]=> string(14) "Lun 18-01-2021" [4]=> string(14) "Mie 20-01-2021" [5]=> string(14) "Lun 25-01-2021" } [1]=> array(85) { ["Pedro"]=> array(21) { ["Lun 11-01-2021"]=> string(2) "SI" ["Mie 13-01-2021"]=> string(2) "SI" ["Lun 18-01-2021"]=> string(2) "SI" ["Mie 20-01-2021"]=> string(0) "" ["Lun 25-01-2021"]=> string(0) "" } ["Maria"]=> array(21) { ["Lun 11-01-2021"]=> string(2) "SI" ["Mie 13-01-2021"]=> string(2) "SI" ["Lun 18-01-2021"]=> string(0) "" ["Mie 20-01-2021"]=> string(0) "" ["Lun 25-01-2021"]=> string(0) "" } } }
And here is my code (the variables $listaFechas
and $paraCSV
are arrays themselves):
$listaParaCSV = array ( $listaFechas, $paraCSV ); $fp = fopen('backupAsistenciaCurso-'.$cursoID.'.csv', 'w'); foreach ($listaParaCSV as $fields) { fputcsv($fp, $fields); } fclose($fp);
The expected result is a CSV file that when opened with open with OpenCalc or excel shows something like this:
Advertisement
Answer
The problem is that you are looping over the $listaParaCSV
with has 2 elements, the headers and then all the data in one element.
Instead, if you write out the headers and then loop over $paraCSV
, adding the key (the name) as the first field before outputting them…
$fp = fopen('backupAsistenciaCurso-'.$cursoID.'.csv', 'w'); fputcsv($fp, $listaFechas); foreach ($paraCSV as $key => $fields) { array_unshift($fields, $key); fputcsv($fp, $fields); }