我正在尝试从 JSON(如下)中获取值并将它们插入到现有 CSV 的新列中。使用我当前的代码(也在下面),添加到新行的所有内容都是每行上的单词“Array”。如何调整我的代码以使其正常工作?另外,有没有办法为我正在创建的新列设置标题名称?
谢谢,请看下面我的代码,如果您有任何问题,请告诉我。
JSON 块:
{
"test":{"12345":"98765","56789":"54321"},
"control":{"99999":"987651","88888":"987652","22222":"987653","27644":"987655"}
}
当前 CSV:
userid,foo_date,bar,baz,qux,country
"12345","2013-03-14","1.72500","1","1055.74","UK"
"38726","2013-03-14",\N,"1","3430.07","UK"
"85127","2013-03-14",\N,"0","635.25","US"
"16984","2013-03-14",\N,"1","5233.09","US"
当前 PHP(根据How to add columns to CSV using PHP):
$json = json_decode($s, true);
$json_values = array_values($json['control']);
$newCsvData = array();
if (($handle = fopen("testgroup.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = $json_values;
$newCsvData[] = $data;
}
fclose($handle);
}
$handle = fopen('testgroup.csv', 'w');
foreach ($newCsvData as $line) {
fputcsv($handle, $line);
}
fclose($handle);
$s
等于 JSON blob。
生成的 CSV 应如下所示:
userid,foo_date,bar,baz,qux,country,extra
"12345","2013-03-14","1.72500","1","1055.74","UK","987651"
"38726","2013-03-14",\N,"1","3430.07","UK","987652"
"85127","2013-03-14",\N,"0","635.25","US","987653"
"16984","2013-03-14",\N,"1","5233.09","US","987655"