PHP JSON Array Merge

by Vincy. Last modified on July 6th, 2023.

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

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

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

↑ Back to Top

Share this page