How to merge two JSON objects in PHP

Summary:

Use the json_decode, array_merge, json_encode functions if you want to merge 2 json objects in PHP. Convert the json object into a PHP array, merge it and then convert it back into json.

Learn How to Merge two JSON Objects in PHP

Javascript Object Notation (JSON) is a text based representation of structured data and a lightweight data exchange format. Various APIs provide JSON data, and developers have to parse that JSON at their end. So, JSON has become a communication source between the client and the server.

merge two json objects in php

So, developers write functions to consume JSON data correctly in their applications. PHP has some useful functions for dealing with JSON, and this article will use these functions to merge two JSON objects in PHP. Instead of jumping in straight to the main topic, we recommend going through these functions to have solid ground.

#1 – User Data – Merge two JSON objects in PHP

Let’s emulate two JSON objects containing data for a bunch of users. The two objects have to be merged. Here are the JSON objects.


[
    {
        "id": "0",
        "name": "Arthur Morgan",
        "age": "30",
        "online": false
    },
    {
        "id": "1",
        "name": "John Marsh",
        "age": "30",
        "online": true
    },
    {
        "id": "2",
        "name": "Stacia Kendell",
        "age": "22",
        "online": false
    }
]

[
    {
        "id": "3",
        "name": "Dave Johnson",
        "age": "34",
        "online": true
    },
    {
        "id": "4",
        "name": "Ria Saleh",
        "age": "28",
        "online": true
    },
    {
        "id": "5",
        "name": "Tim Lee",
        "age": "25",
        "online": false
    }
]

So, how to go about this problem and merge these JSON objects in PHP? Here’s one way of merging these JSON objects.

//The array_decode converts the JSON into a PHP associative array.
$json_array_first = json_decode($json_obj_first, true);
$json_array_second = json_decode($json_obj_second, true);
 
//The array_merge combines both the JSON objects.
$merged_json_object = array_merge($json_array_first, $json_array_second);
 
$encoded_merged_json = json_encode($merged_json_object, JSON_PRETTY_PRINT);

Here’s a textual description of the example.

  • The json_decode function to first convert the JSON objects to PHP associative arrays.
  • Then, the array_merge combines these JSON arrays.
  •  Finally, the json_encode converts the array back to JSON objects.

The example above intentionally spanned over a few lines. Here’s a more compact version.

$encoded_merged_json = json_encode(array_merge(json_decode($json_obj_first, true), json_decode($json_obj_second, true)), JSON_PRETTY_PRINT);

The output of the example is.

[
    {
        "id": "0",
        "name": "Arthur Morgan",
        "age": "30",
        "online": false
    },
    {
        "id": "1",
        "name": "John Marsh",
        "age": "30",
        "online": true
    },
    {
        "id": "2",
        "name": "Stacia Kendell",
        "age": "22",
        "online": false
    },
    {
        "id": "3",
        "name": "Dave Johnson",
        "age": "34",
        "online": true
    },
    {
        "id": "4",
        "name": "Ria Saleh",
        "age": "28",
        "online": true
    },
    {
        "id": "5",
        "name": "Tim Lee",
        "age": "25",
        "online": false
    }
]


That’s not the end yet because another way to merge JSON objects in PHP is using the array_splice instead of the array_merge. Let’s redo the example with the array_splice function.

//The array_decode converts the JSON into a PHP associative array.
$json_array_first = json_decode($json_obj_first, true);
$json_array_second = json_decode($json_obj_second, true);
 
//The array_splice combines both the JSON objects.
array_splice($json_array_first, count($json_array_first), 0, $json_array_second);
 
$encoded_merged_json = json_encode($json_array_first, JSON_PRETTY_PRINT);

The example is almost identical except that array_merge has been replaced with the array_splice. An important note here is that the array_splice does in-place array modifications.

#2 – Config Data – Merge two JSON objects in PHP

JSON is also convenient for representing configuration settings. The intuitive “KEY/VALUE” pairs are ideal for annotating setting files. Let’s mock a scenario where the latest configuration file has to overwrite the current one. Here is the JSON for both.


{
    "version" : 8.0,
    "root": "index.js",
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6"
      },
    "include": ["node"]
}
{
    "version" : 7.0,
    "root": "index.js",
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5"
      },
    "include": ["node"]
}

At a glance, it is obvious that these two can not be merged the way we did in the last example. A sane approach is that the latest overwrites the current. So, what is the way out? Let’s check out.

//The array_decode converts the JSON into a PHP associative array.
$json_array_first = json_decode($json_obj_first, true);
$json_array_second = json_decode($json_obj_second, true);
 
//The array_splice combines both the JSON objects.
$merged_json_array = array_merge($json_array_first, $json_array_second);
 
$encoded_merged_json = json_encode($merged_json_array, JSON_PRETTY_PRINT);

Isn’t it the exact code? Yes, it is. The quirk here is that the array_merge function overwrites similar keys with the latest values. So, when it encounters identical keys, it replaces their value with the values from the second argument, which are our latest configurations. Life made easy!

Conclusion

This article shows how to merge two JSON objects in PHP. The first example emulates two JSON objects having user-related data and merges them using the array_merge and array_splice PHP functions. Finally, the article looks at another perspective and mocks two JSON configuration objects. The latest configuration overwrites the current through PHP array_merge. 

Hopefully, this article has been helpful. If you are interested in learning new functions and tutorials in PHP, do not miss out on content at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


Article Categories

Article Tags

© 2022 Confident.Systems