将 Json 数组导出到 php 中的 CSV

Export Json Array to CSV in php

我有这个供应商数组

[
    {
        "reference":"01042",
        "images":   [
            "http:\/\/static1.provider.com\/34\/01042.jpg"
        ]
    },
    {
        "reference":"01057",
        "images":[
            "http:\/\/static1.provider.com\/57\/01057.jpg",
            "http:\/\/static3.provider.com\/58\/01057.jpg",
            "http:\/\/static2.provider.com\/59\/01057.jpg"]
    },
    ...
]

我用下面的代码导出

$json_file2 = file_get_contents('http://direct.provider.com/public/ref_urlimage_20.json', false);

$decoded = json_decode($json_file2);

$fp = fopen('imagenes.csv', 'w');
foreach($decoded as $comment) {
    fputcsv($fp, $comment);
}
fclose($fp);

但它显示了以下结果

01104,Array
01119,Array
40460,Array
00311,Array
00312,Array
00307,Array

当您需要导出为这种格式时

01104,http://static3.provider.com/155/01119.jpg
01119,http://static3.provider.com/155/04519.jpg,http://static3.provider.com/155/01148.jpg,http://static3.provider.com/155/0859.jpg
40460,http://static3.provider.com/155/01119.jpg,http://static3.provider.com/155/01118.jpg
00351,http://static3.provider.com/175/07219.jpg
...

我哪里做错了? 谢谢

if (empty($argv[1])) die("The json file name or URL is missed\n");
$jsonFilename = $argv[1];

$json = file_get_contents($jsonFilename);
$array = json_decode($json, true);
$f = fopen('output.csv', 'w');

$firstLineKeys = false;
foreach ($array as $line)
{
    if (empty($firstLineKeys))
    {
        $firstLineKeys = array_keys($line);
        fputcsv($f, $firstLineKeys);
        $firstLineKeys = array_flip($firstLineKeys);
    }
    $line_array = array($line['reference']);
    foreach ($line['images'] as $value)
    {
        $line_array.push($value);
    }
    fputcsv($f, $line_array);

}

因为你有数组内部循环像上面的代码可能有助于解决问题

试试下面的代码,这行得通

<?php
//if (empty($argv[1])) die("The json file name or URL is missed\n");
//$jsonFilename = $argv[1];
//
//$json = file_get_contents($jsonFilename);
$json_file2 = file_get_contents('http://direct.funidelia.es/public/ref_urlimage_20.json', false);
error_reporting(E_ALL);
//echo $json_file2;die;
    $json='{"data":'.$json_file2.'}';
//echo $json;
$array = json_decode($json, true);
//echo "<pre>";
//print_r($array);
//die;
$f = fopen('output.csv', 'w');

$firstLineKeys = false;
foreach ($array["data"] as $line)
{
//    echo "<pre>";
//    print_r($line);
//    die;
    if (empty($firstLineKeys))
    {
        $firstLineKeys = array_keys($line);
        fputcsv($f, $firstLineKeys);
        $firstLineKeys = array_flip($firstLineKeys);
    }
    $line_array = array($line['reference']);

    foreach ($line['images'] as $value)
    {
        array_push($line_array,$value);
    }
    fputcsv($f, $line_array);

}
echo "Success";
?>