fputcsv()将所有数据放在一行中

时间:2018-04-16 01:13:40

标签: php arrays fputcsv

我正在阅读一些json,将其展平为单个数组,然后将其写入csv。我已经走得很远,但我目前只停留在最后一个组件上。我能够提取数据,压平数据并将其写入csv,但由于某种原因,它将所有数据写入一行,而它应该为每个新对象创建一个新行。我认为它正在发生,因为我的扁平阵列正在采用多个对象并将它们组合成一个,但我无法弄清楚如何修复它。任何帮助将不胜感激。

以下是我所拥有的:

<?php

$csvArray = array();

function array_flatten($array, $prefix = 'new')
{
if (!is_array($array)) {
    return false;
}
$result = array();
foreach ($array as $key => $value) {
    if (is_array($value)) {
        $result = array_merge($result, array_flatten($value, $prefix . '_' . $key));
    } else {
        $result[$prefix . '_' . $key] = $value;
    }
}
return $result;
}

for ($x = 1; $x <= 1; $x++) {

$response = file_get_contents('https://seeclickfix.com/api/v2/issues?page=' . $x . '&per_page=2');

//Decode the JSON and convert it into an associative array.
$jsonDecoded = json_decode($response, true);

$flat = array_flatten($jsonDecoded['issues']);

//Give our CSV file a name.
$csvFileName = '/Applications/MAMP/htdocs/SeeClickFix/all_exports_3/export' . $x . '.csv';

//Open file pointer.
$fp = fopen($csvFileName, 'w');

foreach ($flat as $item) {
    // fputcsv($fp, $item);


    if (is_null($item) || !isset($item) || $item == "Point") {

    } else {

        array_push($csvArray, $item);

    }

  fputcsv($fp, $csvArray);

}


 fclose($fp);



}





?>

0 个答案:

没有答案