user348246
user348246

Reputation: 380

put array contents into csv column

I have a date array:

$date = array();

and a name array:

$name = array();

and I created a bidimensional array, or array in array

$allinone = array($date,$names);

and with this php I put them into csv:

$fp = fopen('download.csv', 'w');
foreach ($allinone as $key => $values) {
    fputcsv($fp, $values);
}
fclose($fp);

with this it looks like:

enter image description here

but I want to achieve to transpose them to column, like this:enter image description here

How to make this to work? I tried array_combine and merge but does not helped me.

Thank you your time!

Upvotes: 1

Views: 498

Answers (1)

u_mulder
u_mulder

Reputation: 54796

I suppose you can just iterate over one array, controlling it's key and output it's value along with value of the same key of the second array:

$fp = fopen('download.csv', 'w');
foreach ($date as $key => $value) {
    fputcsv($fp, array($value, $name[$key]));
}
fclose($fp);

If source arrays have different keys, you can reindex both arrays to numeric keys with array_values:

$date = array_values($date);
$name = array_values($name);

$fp = fopen('download.csv', 'w');
foreach ($date as $key => $value) {
    fputcsv($fp, array($value, $name[$key]));
}
fclose($fp);

Upvotes: 2

Related Questions