例如,如果我有一个像这样的简单JSON:
{
"data": [
"pets" : "none",
"parents": {"mom":"Anna", "dad":"Bob"},
"ancestors": { "children":[
{
"name": "Joe",
"age" : "10"
},
{
"name" : "Ron",
"age" : "4"
}
]}
]
}
假设我想用PHP添加一个“ 8”岁的孩子“ Jessica”,我该怎么做?到目前为止,我知道我需要使用json_decode来访问JSON,使用json_encode来保存其中的内容,但是如果我需要添加$newchild = array("name" : "Jessica", "age" : "8");
并添加它,它将如何在data-> ancestors-> children中进行呢?
当您使用json_decode时,您正在将json字符串转换为php数组
因此,您可以像这样添加新元素:
$jsonstring = '...the string...';
$jsonarray = json_decode($jsonstring, true);
$jsonarray['data']['ancestors']['children'][] = array('name'=>'Jessica', 'age'=>8);
制作print_r$jsonarray
的内容
然后您当然可以再次将其打印到json字符串
$jsonstring = json_encode($jsonarray);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句