简体   繁体   中英

how to add a nested element in already existing JSON with PHP

for example if I have a simple JSON like this:

{
 "data": [
  "pets" : "none",
  "parents": {"mom":"Anna", "dad":"Bob"},
  "ancestors": { "children":[
   {
    "name": "Joe",
    "age" : "10"
   },
   {
    "name" : "Ron",
    "age" : "4"
   }
  ]}
 ]
}

and let's say I want to add a child "Jessica" of age "8" with PHP how would i do that? so far I know i need to use json_decode to access the JSON, json_encode to save something in it but if I need to add a $newchild = array("name" : "Jessica", "age" : "8"); and add it how would it do it in data->ancestors->children ?

When you use json_decode, you are converting the json string to php array

So, you can add the new element like so:

$jsonstring = '...the string...';
$jsonarray = json_decode($jsonstring, true);
$jsonarray['data']['ancestors']['children'][] = array('name'=>'Jessica', 'age'=>8);

Make print_r of the $jsonarray to see it's contents

and then of course you could print it again to json string

$jsonstring = json_encode($jsonarray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM