这是我的问题。我有这样一个JSON文件:
[
{
"projectName": "test",
"clientName": "test2",
"dateValid": "2014-04-18",
"account": {
"accountAmount": null,
"accountDate": "2014-04-19",
"accountType": null
},
"total": {
"totalAmount": null,
"totalDate": "2014-04-18",
"totalType": null
}
}]我希望PHP打开这个文件并添加另一个对象,所以我的文件如下所示:
[
{
"projectName": "test",
"clientName": "test2",
"dateValid": "2014-04-18",
"account": {
"accountAmount": null,
"accountDate": "2014-04-19",
"accountType": null
},
"total": {
"totalAmount": null,
"totalDate": "2014-04-18",
"totalType": null
}
},
{
"projectName": "test",
"clientName": "test2",
"dateValid": "2014-04-18",
"account": {
"accountAmount": null,
"accountDate": "2014-04-19",
"accountType": null
},
"total": {
"totalAmount": null,
"totalDate": "2014-04-18",
"totalType": null
}
}
]这应该很简单,但我做不到。我试过多种方法去做:
$file = 'base.json';
if(file_exists ($file)){
echo 'base.json found';
$fileContent = file_get_contents($file);
$oldData = json_decode($fileContent, true);
echo var_export($oldData);
}
else {
echo 'base.json not found';
$oldData = [];
}
echo $data;
$data = json_encode($data);
$oldData = json_encode($oldData);
echo $data; // debug
file_put_contents('base.json', '['.$data.','.$oldData.']');是的,我放了很多回波来调试数据处理.我错过了什么?
发布于 2014-04-22 17:44:29
使用以下方法将新数据添加到数组中:
$oldData[] = $data;然后将其写回文件:
file_put_contents('base.json', json_encode($oldData));发布于 2014-04-22 17:40:57
你把它当作字符串操作,这是绝对错误的方法。在将这两个结构重新编码为JSON之前,需要在它们是对象时组合它们。
这三行..。
$data = json_encode($data);
$oldData = json_encode($oldData);
file_put_contents('base.json', '['.$data.','.$oldData.']');应该重写为..。
// Create a new array with the new data, and the first element from the old data
$newData = array($data, $oldData[0]);
$newData = json_encode($newData);
file_put_contents('base.json', $newData);发布于 2014-04-22 17:53:02
您可以将json转换为数组,在json_decode上指定第二个param为true,然后使用array_merge来包含新的数组var并再次转换为json。
<?php
$json1 = '[{
"projectName": "test",
"clientName": "test2",
"dateValid": "2014-04-18",
"account": {
"accountAmount": null,
"accountDate": "2014-04-19",
"accountType": null
},
"total": {
"totalAmount": null,
"totalDate": "2014-04-18",
"totalType": null
}
}]';
$json2 = '[{
"projectName": "test 2",
"clientName": "test3",
"dateValid": "2014-04-22",
"account": {
"accountAmount": null,
"accountDate": "2014-04-27",
"accountType": null
},
"total": {
"totalAmount": null,
"totalDate": "2014-04-27",
"totalType": null
}
}]';
$arr1 = json_decode($json1, true);
$arr2 = json_decode($json2, true);
$json2 = json_encode(array_merge($arr1, $arr2));
?>https://stackoverflow.com/questions/23226530
复制相似问题