Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

When trying to export this array as a CSV file in php I get an empty sheet

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...