I am trying to take values from JSON (below) and insert them into a new column of an existing CSV. With my current code (also below), all that's being added to the new row is the word "Array" on each line. How can I adjust my code so that it works properly? Also, is there a way for me to set a header name for the new column I'm creating?
Thank you, please look at my code below and let me know if you have any questions.
JSON blob:
{
"test":{"12345":"98765","56789":"54321"},
"control":{"99999":"987651","88888":"987652","22222":"987653","27644":"987655"}
}
Current 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"
Current PHP (as per 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 equals the JSON blob.
Resulting CSV should look like:
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"