I have an array of arrays
$numbers= array(3) {
[months]=>
array(3) {
["1"]=>
string(7) "Jan"
["2"]=>
string(7) "Feb"
["3"]=>
string(7) "Mar"
}
[dates]=>
array(3) {
["1"]=>
string(7) "12th"
["2"]=>
string(7) "19th"
["3"]=>
string(7) "22nd"
}
[people]=>
array(3) {
["1"]=>
string(7) "Bill"
["2"]=>
string(7) "Ted"
["3"]=>
string(7) "Gary"
}
}
I want to write the contents of these arrays into a CSV file in the form of a table so I get an output like:
months, dates, people
Jan, 12th, Bill
Feb, 19th, Ted
Mar, 22nd, Gary
I want to try and put it directly from the array into the CSV in one move it it's possible but I can't find a way to do it without cutting it up.
$mi = new MultipleIterator();
$headers = array();
foreach($numbers as $header => $data) {
$mi->attachIterator(new ArrayIterator($data));
$headers[] = $header;
}
$fh = fopen('myfile.csv', 'w');
fputcsv($fh, $headers);
foreach($mi as $values) {
fputcsv($fh, $values);
}
fclose($fh);
<?php
// transform the array
$keys = array_keys($numbers);
array_unshift($numbers, null);
$output = call_user_func_array('array_map', $numbers);
array_unshift($output, $keys);
// from php.net
$fp = fopen('file.csv', 'w');
foreach ($output as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.