tags:

views:

44

answers:

2

i used json_decode to create a json object. After going through some elements i would like to add child elements to it. How do i do this?

A: 

I would use json_decode($json,true) with the true flag so that it would come back as an associative array. Then you can add items using the array syntax.

easement
+1  A: 

Depending on which options you passed to json_decode(), you got either an object or array back from it, and you can add elements to these as you would any other object or array.

To add $key => $element to an array:

$myArray[$key] = $element;

Slightly less obvious, but you can add a new public member to an object in PHP as follows:

$myObj->$key = $element;

This will add a member variable from the contents of $key (assuming $key is a string).

If you then pass your array/object into json_encode(), you'll end up with the following json:

{ 'value_of_key' : 'value_of_element' }
therefromhere
I didnt realize changing the option would make it better. Thanks. Its easier to access and i know how to write to it now.
An employee