在PHP中格式化数组,使用fputcsv输出到csv
I have an array in this format:
That I want to output to csv. The trouble I'm having is getting that array in the right format. When I do:
foreach ($array as $row) {
fputcsv($df, $row);
}
I only get the integer values. I am missing a column with the names like ACCESSORIES
.
Here is the output:
But I want column A to have the names like ACCESSORIES
and column B to have the values.
我有一个这种格式的数组: p>
p>
我要输出到csv。 我遇到的麻烦是以正确的格式获取该数组。 当我这样做时: p>
foreach($ array as $ row){
fputcsv($ df,$ row);
}
code> pre >
我只获取整数值。 我缺少一个名为 ACCESSORIES code>的列。 p>
这是输出: p>
p>
但我希望列A的名称类似于 ACCESSORIES code >和列B具有值。 p>
div>
fputcsv
just outputs the array values; the keys would usually be column names, not additional columns in the row. You need to make an array out of each element's key and value.
foreach ($array as $row) {
$keys = array_keys($row);
fputcsv($df, array($keys[0], $row[$keys[0]]));
}
You can use the iteration loop of foreach like that :
foreach ($array as $key => $value) {
fputcsv($df, array($key[0], $value[$key[0]]));
}
it will help you ,I used my array like :
Array
(
[0] => Array
(
[NUMBER] => 67
[TYPE] => Other
[DATE] => 3/31/2011
)
[1] => Array
(
[NUMBER] => 87
[TYPE] => something
[DATE] => 3/28/2011
)
[2] => Array
(
[NUMBER] => 67
[TYPE] => Other
[DATE] => 3/2/2011
)
)
<?php
$fp1 = fopen('file.csv', 'w');
foreach ($arr2 as $fields)
{
fputcsv($fp1, $fields);
}
fclose($fp1);
?>