我有一个像这样结构的数组
[cars] => Array
(
[0] => 43063
[1] => 17306
[2] => 116078
)
[houses] => Array
(
[0] => 13300
[1] => 32243
)
[garage] => Array
(
[0] => 13094
[1] => 30649
)
[hotels] => Array
(
[0] => 10025
[1] => 59468
[2] => 29734
)
我想从该数组中创建一个csv文件。我的csv文件应该以这种方式构建 汽车,43063,17306,116078 房子,13300,32243,1000 车库,13094,30649,1000 宾馆,10025,59468,29734
我已经尝试了几个代码,但是我没有得到我想要的东西,我怎么能在php中实现呢?
这是我的数组
的var转储array(4) {
["23"]=>
array(1) {
["cars"]=>
int(43063)
}
[23]=>
array(4) {
["cars"]=>
int(17306)
["houses"]=>
int(13300)
["garage"]=>
int(13094)
["hotels"]=>
int(10025)
}
[22]=>
array(4) {
["cars"]=>
int(116078)
["houses"]=>
int(32243)
["garage"]=>
int(30649)
["hotels"]=>
int(59468)
}
[21]=>
array(1) {
["hotels"]=>
int(29734)
}
}
我想要一个包含4行的csv,每个键一行(酒店,汽车,车库等等。
cars,43063,17306,116078
houses,13300,32243,1000
garage,13094,30649,1000
hotels,10025,59468,29734
答案 0 :(得分:1)
你可以试试这样的事情
function arrayToValues(array $data)
{
$output = array();
foreach ($data as $key => $item) {
if (is_array($item)) {
$output = array_merge($output, array($key), arrayToValues($item));
} else {
$output[] = $item;
}
}
return $output;
}
$csvData = implode(',', arrayToValues($yourArrayData));
如果您想编写输出,可以将fputcsv与函数结合使用。
答案 1 :(得分:0)
又快又脏:
foreach ($arr as $key => $vals) {
echo $key . implode(",", $vals) . "\n";
}
更新:
$transformed = array();
foreach ($arr as $item) {
foreach ($item as $key => $val) {
$transformed[$key][] = $val;
}
}
foreach ($transformed as $key => $vals) {
echo $key . implode(",", $vals) . "\n";
}