0

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

1
  • I cant see your $listaFechas and $paraCSV, Check the format of these two array Commented Jan 12, 2021 at 15:24

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.