Adding data to json with PHP
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 to share