Merge two JSON objects using PHP: 3 Code Examples (2023)

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Learn How to Merge two JSON Objects in PHP

There are three steps to merge two JSON objects with PHP. First, use the json_decode function to convert to PHP array. Second, use the array_merge function to merge them. Finally, use the json_encode function to convert them back to JSON.

Steps to Merging JSON Data in PHP

  • convert to PHP array: json_decode
  • merge PHP arrays: array_merge
  • convert back to JSON: json_encode

What is JSON

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. JSON has become a communication source between the client and the server.

merge two json objects in php

Developers write functions to consume JSON data correctly in their applications.

PHP has some useful functions for dealing with JSON. We will use these function to merge multiple JSON objects.

Instead of jumping in straight to the main topic. We recommend going through these functions to have solid ground.

Merge two JSON objects in PHP Code Example

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!

How to Merge 2 JSON Objects Using PHP

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.

Click here to read an excellent article on joining & appending multiple PHP strings together.

Using JSON in PHP Article Series

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.