Skip to content
Advertisement

Add to a JSON object, with PHP

I’d like to increment a JSON object with a new given one but I can’t do it. I have the following JSON:

JavaScript

The user will create more fields and I’d like to insert in the original JSON the new field that comes in this format:

JavaScript

Advertisement

Answer

Looks like you’re trying to add new elements to the root JSON object, in which case you simply need to:

  1. Decode the JSON objects into PHP arrays.
  2. Merge the arrays into one.
  3. Encode the merged array back into JSON.
JavaScript

The final $json object will be:

JavaScript

If you want to add the fields into a JSON array, rather than an object, you can do this instead:

JavaScript

Which results in:

JavaScript

Note

If you try to add your original second field as you have given it in your question, it won’t work because it’s not a fully formatted JSON string. You must ensure it has the outer pair of curly braces.

Incorrect:

JavaScript

Correct:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement