Adding data to json with PHP

I have used json_decode to create a json object. After going through a few elements, I would like to add children to them. How to do it?

+2


source to share


2 answers


Depending on what parameters you passed in json_decode()

, you got either an object or an array from it, and you can add elements to them just like any other object or array.

Add $key => $element

to array:

$myArray[$key] = $element;

      

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



$myObj->$key = $element;

      

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

If you then pass your array / object in json_encode()

, you get the following json:

{ 'value_of_key' : 'value_of_element' }

      

+5


source


I would use json_decode($json,true)

with a true flag so that it returns as an associative array. Then you can add items using array syntax.



+1


source







All Articles