使用php将项添加到json

使用php将项添加到json,php,json,Php,Json,我很困惑,无法向json对象正确添加新对象: $old_json = json_decode(file_get_contents("file.json"), true); $new_json = ' { "1" : "111", "2" : "222" } '; $old_json[] = $new_json; file_put_contents("file.json", stripslashes(json_encode($old_json))); 它将用新记录替换旧记录,但我只想添加新记

我很困惑,无法向json对象正确添加新对象:

$old_json = json_decode(file_get_contents("file.json"), true);

$new_json = ' { "1" : "111", "2" : "222" } ';
$old_json[] = $new_json;

file_put_contents("file.json", stripslashes(json_encode($old_json)));
它将用新记录替换旧记录,但我只想添加新记录。我希望它编写新的json文件,包含以下内容:

[{"a":"aaa","b","bbb"},{"1":"111","2":"222"}]
请告诉我如何取得正确的结果。另外,请告诉我如何在json_decode()之后访问新的json对象


谢谢。

当字符串从
json
转换为
php变量
时,此过程将生成一个
stdClass对象
。简单地说,您不想添加到对象(此处)。尽管您可以创建
stdClass对象
,然后重新生成一个新的
json
对象。

条带斜杠是用来做什么的?原始输入看起来如何?为什么不在解码后作为一个普通数组追加呢?首先,在
文件中有一个额外的
“file.json”,stripslashes(json\u encode($old\u json))在末尾,除非它是另一个开口的一部分
功能