Search code examples
phparrayscsvfputcsv

How to write 2 arrays in csv file using php


I want to write 2 arrays in a csv file and display it horizontally.

Array 1

Array
(
    [0] => Array
        (
            [0] => 501
            [1] => 8921
        )

    [1] => Array
        (
            [0] => 502
            [1] => 8446
        )
)

Array 2

Array
(
    [0] => Array
        (
            [0] => 501
            [1] => 8900
        )

    [1] => Array
        (
            [0] => 502
            [1] => 8436
        )
)

Code to write in csv file:

header("Content-type: text/csv; charset=utf-8; encoding=utf-8");
header("Content-Disposition: attachment; filename={$exportFileName}.csv");
header("Pragma: no-cache");
header("Expires: 0");

$file = fopen('php://output', 'w');
fputcsv($file, array('HID', 'WEEK1', 'HID', 'WEEK2')); 
foreach  ($fweek as $k=>$row) 
{
    fputcsv($file, $row);  // I want to include $sweek as well             
}

But currently, it displays only the first array.

Any hint/suggestion will do a great help. Thanks in advance.


Solution

  • If they are always going to be lined up, you could use the key of the foreach to that other array and merge them. Like this:

    foreach($fweek as $k => $row) {
        $row = array_merge($row, $sweek[$k]);
        fputcsv($file, $row);
    }