Search code examples
phpcsvfputcsv

Move pointer horizontally using fputcsv in PHP


I am trying to write 2 arrays to csv file using fputcsv.

But the problem is when writing the second array it goes to the end of the file and starts from there.

So basically I have these 2 sections to write in a csv file and it's writing in the following way

ID      Name1

1       AAA
2       BBB

Name2

CCC
DDD

What I want

ID      Name1      Name2

1       AAA        CCC
2       BBB        DDD

My code is

fputcsv($fh, array("ID","Name1"));
while($row = mysqli_fetch_array($weekly1, MYSQLI_NUM))
{
    fputcsv($fh, array($row[0],$row[1]));
}

fputcsv($fh, array("Name2"));
while($row = mysqli_fetch_array($weekly2, MYSQLI_NUM))
{
    fputcsv($fh, array($row[1]));
}

Is there any way to overcome this problem. Any help or suggestion is highly welcomed.Thanks in advance.


Solution

  • First you should store ID and NAME1 in an array and only after getting NAME2 save to csv:

    fputcsv($fh, array("ID","Name1","Name2"));
    $rows = array();
    while($row = mysqli_fetch_array($weekly1, MYSQLI_NUM))
    {
        $rows[] = array($row[0],$row[1]));
    }
    
    $i = 0;
    while($row = mysqli_fetch_array($weekly2, MYSQLI_NUM))
    {
        fputcsv($fh, array_merge($rows[$i], array($row[1])));
        $i++;
    }