PHPIntermediate

PHP JSON Array Merge

PB Pb28 Master Team July 6th, 2023 Intermediate

📦 Get the complete source code for this tutorial

Merging one or more JSON arrays using PHP can be done in various ways. For example, the merge can be done using PHP array_merge() function or by pushing each JSON array into a target array.

You can glance at one of my previous articles if you are looking for a beginner’s guide to learn more about JSON handling with PHP.

In this tutorial, we will use one of the easiest methods of merging JSON arrays using PHP. For that, the input JSON has to be decoded before merging.

Previously, we have seen decoding given JSON objects and encoding. About the example code that we had seen in the linked article, we will proceed to decode before merging JSON arrays.

In this example, we have two JSON objects to merge. These objects will be decoded into an associative array and encoded after the array merge.

php_json_merge

PHP JSON Merge

This code is used to merge given two JSON objects

php-template
<?php

$json1 = '{

	"id": "#001",

    "username": "Tom",

    "type": "admin",

    "status": "active"

}';



$json2 = '{

    "id": "#002",

    "username": "Jerry",

    "type": "user",

    "status": "Inactive"

}';

$user[] = json_decode($json1, true);

$user[] = json_decode($json2, true);

$json_merge = json_encode($user);

?>



<h4>Given JSON String:</h4>

<div>

	<div>$json1 = <?php echo $json1; ?></div>

	<div>$json2 = <?php echo $json2; ?></div>

</div>

<h4>Output:</h4>

<div><?php echo $json_merge; ?></div>

Output

output

Download

📦 Download the full project files and try it locally