-1

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.

Grant
  • 2,241
  • 2
  • 26
  • 38
Raj
  • 1,275
  • 3
  • 20
  • 40

1 Answers1

1

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++;
}
u_mulder
  • 51,564
  • 5
  • 39
  • 54
  • Ahh I see. Let me try. Thanks mate. – Raj Dec 17 '14 at 20:59
  • Also try to make one SQL query for getting data, if it's possible, then you will do one loop only and can write to csv immediately. – u_mulder Dec 17 '14 at 21:04
  • Yes I agree but the situation is that I have to write multiple query as I am making a weekly/monthly report.It's complicated :( – Raj Dec 17 '14 at 21:08