2

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?

1
  • 1
    I think you mean json_encode. json_decode will convert a string in JSON format to a equivalent PHP representation while json_encode will do the reverse (converting a PHP representation to a string in JSON format). Commented Oct 6, 2009 at 13:52

2 Answers 2

5

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' }
Sign up to request clarification or add additional context in comments.

1 Comment

I didnt realize changing the option would make it better. Thanks. Its easier to access and i know how to write to it now.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.