adding data into json with PHP

json, php

Solution

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' }

Problem

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?

Original source