我想用PHP在JSON文件中推送新对象,但由于格式原因,我在互联网上找不到任何解决方案。
这是我的Json文件。
{
"html": {
"snippet1": {
"id":"snippet1",
"title":"A title"
},
"snippet2": {
"id":"snippet2",
"title":"Another title"
}
}
}
这是PHP文件
$json = file_get_contents('./content.json');
$data = json_decode($json);
$id = "snippet3";
$title= "My title";
我希望将这些新数据推送到JSON中。
结果应为:
{
"html": {
"snippet1": {
"id":"snippet1",
"title":"A title"
},
"snippet2": {
"id":"snippet2",
"title":"Another title"
},
"snippet3": {
"id":"snippet3",
"title":"My title"
}
}
}
谢谢
$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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句