我想使用PHP将新对象推送到JSON文件中,但由于格式原因,我在互联网上找不到任何解决方案。
这是我的Json文件。
mysqldump
这是php文件
{
"html": {
"snippet1": {
"id":"snippet1",
"title":"A title"
},
"snippet2": {
"id":"snippet2",
"title":"Another title"
}
}
}
我希望将这些新数据推送到JSON中。
结果应为:
$json = file_get_contents('./content.json');
$data = json_decode($json);
$id = "snippet3";
$title= "My title";
谢谢
答案 0 :(得分:1)
$json = file_get_contents('./content.json');
$data = json_decode($json, true); //added true to make it an array
$id = "snippet3";
$title = "My title";
$data['html'][$id]['id'] = $id; //add the id to the array
$data['html'][$id]['title'] = $title; //add the title to the array
$newData = json_encode($data, true); //turn the array back into json
$writeJson = file_put_contents("content.json", $newData); //write the json array to json file