0

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 ?

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.