使用PHP将新的JSON对象添加到数组中

eng*_*nws 0 php json

这是我的问题.我有一个像这样的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
    }
}]
Run Code Online (Sandbox Code Playgroud)

我希望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
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

它应该很简单,但我无法做到这一点.我尝试了多种方法来做到这一点:

$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.']');
Run Code Online (Sandbox Code Playgroud)

是的,我投入了大量的回声来调试数据流程......我缺少什么?

mea*_*gar 5

你将此视为字符串操作,这是一种错误的方法.在将两个结构重新编码为JSON 之前,需要将这两个结构组合在一起.

这三条线......

$data = json_encode($data);
$oldData = json_encode($oldData);
file_put_contents('base.json', '['.$data.','.$oldData.']');
Run Code Online (Sandbox Code Playgroud)

应改写为......

// 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);
Run Code Online (Sandbox Code Playgroud)