CookieMonster
CookieMonster

Reputation: 216

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 ?

Upvotes: 0

Views: 77

Answers (1)

Nik Chankov
Nik Chankov

Reputation: 6047

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);

Upvotes: 2

Related Questions