Search code examples
phparraysmultidimensional-arrayfputcsv

2d array to fputcsv not working


My array looks like this;

Array
(
 [0] => January
 [1] => 2015-01-30
 [2] => 2015-01-15
 [3] => February
 [4] => 2015-02-27
 [5] => 2015-02-18
 [6] => March
 [7] => 2015-03-31
 [8] => 2015-03-18
)

How can I output it to a csv in three columns? One for the Month name, and the other two for the two dates that follow.

At the moment my code looks like this;

$header = array("Month","Date One","Date Two");

$fp = fopen($filename, "w");
fputcsv ($fp, $header, "\t");
foreach($payments_array as $row){
     fputcsv($fp, array($row), "\t");
}
fclose($fp);

The headers go in fine, but I don't know how to get three columns on the data. At the moment at array goes in to the csv all in one column.

I thought array_chuck() might help - but I couldn't work it out.


Solution

  • This should work for you:

    Here I just change the structure from:

    Array
    (
        [0] => January
        [1] => 2015-01-30
        [2] => 2015-01-15
        [3] => February
        [4] => 2015-02-27
        [5] => 2015-02-18
        [6] => March
        [7] => 2015-03-31
        [8] => 2015-03-18
    )
    

    to:

    Array
    (
        [0] => Array
            (
                [0] => January
                [1] => February
                [2] => March
            )
    
        [1] => Array
            (
                [0] => 2015-01-30
                [1] => 2015-02-27
                [2] => 2015-03-31
            )
    
        [2] => Array
            (
                [0] => 2015-01-15
                [1] => 2015-02-18
                [2] => 2015-03-18
            )
    
    )
    

    I do this with splitting the array into chunks of 3 with array_chunk(). After this I just go through the header array and take each array_column() and put it in the $data array. After this you can simply loop through the array as you did and write each line in your .csv file.

    <?php
    
        $arr = array_chunk($arr, 3);
    
        foreach($arr[0] as $k => $v)
            $data[] = array_column($arr, $k);
    
    
        $fp = fopen($filename, "w");
        foreach($data as $row){
             fputcsv($fp, $row, "\t");
        }
        fclose($fp);
    
    ?>
    

    output:

    January February    March
    2015-01-30  2015-02-27  2015-03-31
    2015-01-15  2015-02-18  2015-03-18
    

    EDIT:

    I think I missed something; So this should be what you want:

    <?php
    
        $data = array_chunk($arr, 3);
        $header = array("Month","Date One","Date Two");
    
        $fp = fopen($filename, "w");
        fputcsv($fp, $header, "\t");
        foreach($data as $row){
            fputcsv($fp, $row, "\t");
        }
        fclose($fp);
    
    ?>
    

    output:

    Month   "Date One"  "Date Two"
    January 2015-01-30  2015-01-15
    February    2015-02-27  2015-02-18
    March   2015-03-31  2015-03-18