我正在尝试从JSON(下面)获取值并将它们插入到现有CSV的新列中。使用我当前的代码(也在下面),添加到新行的所有内容都是每行上的“Array”一词。如何调整代码以使其正常工作?另外,有没有办法为我正在创建的新列设置标题名称?
谢谢,请查看下面的代码,如果您有任何问题,请告诉我。
JSON blob:
{
"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"
答案 0 :(得分:2)
试试这个(测试过):
$data = <<<EOF
{
"test":{"12345":"98765","56789":"54321"},
"control":{"99999":"987651","88888":"987652","22222":"987653","27644":"987655"}
}
EOF;
$json = json_decode($data, true);
$json_values = array_values($json['control']);
// add column header to the start of the array
array_unshift($json_values, 'extra');
// open the file in read write mode.
$fd = fopen('testgroup.csv', 'r+');
// add the last field for each record
$records = array();
while($record = fgetcsv($fd)) {
$record []= array_shift($json_values);
$records []= $record;
}
// clear file and set seek to start
ftruncate($fd, 0);
fseek($fd, 0);
// rewrite file
foreach($records as $record) {
fputcsv($fd, $record);
}
fclose($fd);
答案 1 :(得分:0)
另一种快速而天真的方法是:
$json = json_decode($s, true);
$json_values = array_values($json['control']);
$i = 0;
if (($handle = fopen("csvFile.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//seperate your header data
$i++;
if($i==1)
$header = $data;
else
$datas[] = $data; //all the data
$i++;
}
fclose($handle);
}
//adding the json now to the data based on the test value
// assuming that your json data length will be same as number of rows in csv
//you can modify the code easily to make it dynamic
$j=0;
foreach($datas as &$d){
array_push($d, $json_values[$j]);
$j++;
}
//than append data in the file
$handle = fopen('testgroup.csv', 'r+');
//put the header inside the csv
fputcsv($handle, $header);
foreach ($datas as $line) {
fputcsv($handle, $line);
}
fclose($handle);
这是你应该实现的第一种方法,一旦你能够找到一个更好的方法来实现这个,就像@ hek2mgl建议的那样..只是想把它扔出去......
DINS