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
2009-10-06 13:53:11
+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
2009-10-06 13:53:48
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
2009-10-06 14:33:30