PHP JSON Array Merge

by Vincy. Last modified on October 13th, 2022.

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

You can have a glance with one of my previous articles if you are looking for a beginners guide to learn more on JSON handling with PHP.

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

Previously, we have seen about decoding given JSON objects and encoding. With the reference of the example code that we had seen on the linked article, we are going to proceed to decode before merging JSON arrays.

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

Download

php_json_merge

PHP JSON Merge

This code is used to merge given two JSON objects

<?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

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page