在PHP中格式化数组,使用fputcsv输出到csv

时间:2014-05-07 19:08:32

标签: php arrays

我有一个这种格式的数组:

array

我想输出到csv。我遇到的麻烦是以正确的格式获取该阵列。当我这样做时:

foreach ($array as $row) {
   fputcsv($df, $row);
}

我只得到整数值。我遗漏了一个名为ACCESSORIES的列。

这是输出:

csv

但我希望A列的名称如ACCESSORIES和B列都有值。

4 个答案:

答案 0 :(得分:2)

fputcsv只输出数组值;键通常是列名,而不是行中的其他列。您需要从每个元素的键和值中创建一个数组。

foreach ($array as $row) {
    $keys = array_keys($row);
    fputcsv($df, array($keys[0], $row[$keys[0]]));
}

答案 1 :(得分:1)

您可以使用foreach的迭代循环:

foreach ($array as $key => $value) { 
       fputcsv($df, array($key[0], $value[$key[0]]));
    }

答案 2 :(得分:1)

如果有人想将带有动态标题的查询的结果导出到数组,然后导出到 csv 文件,您可以使用以下函数:

function exportCSVFile($fieldsNames, $result)
{

$fileName = "result.csv";
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$fileName");
header("Pragma: no-cache");
header("Expires: 0");
$stdout = fopen('php://output', 'w');

fputcsv($stdout, $fieldsNames, ',', '"'); // put the headers or fields Names

$resultArray = array();

$tempRowHolder = array();

/* 
    build the finalized array which will be used to export the result as csv 
*/

for ($i = 0; $i < count($result); $i++) {
    for ($j = 0; $j < count($fieldsNames); $j++) {
        $tempRowHolder[$j] = $result[$i][$fieldsNames[$j]]; // fetch a row by the different fields names
    }

    /* push the row from the tempRowHolder array to the main array($resultArray) */
    array_push($resultArray, $tempRowHolder);

    /* clear the temporary array (the holder of the row) to use it fresh in the next iteration */
    $tempRowHolder = [];
}

$i = 0;

/* put the finalized array into the csv file  */
while ($i < count($resultArray)) {
    fputcsv($stdout, $resultArray[$i++]);
}

fclose($stdout);
}

答案 3 :(得分:0)

它会帮助你,我使用我的数组:

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);

?>