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?
2 Answers
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' }
1 Comment
An employee
I didnt realize changing the option would make it better. Thanks. Its easier to access and i know how to write to it now.
json_encode.json_decodewill convert a string in JSON format to a equivalent PHP representation whilejson_encodewill do the reverse (converting a PHP representation to a string in JSON format).