PHP JSON Array Merge

Last modified on February 3rd, 2017 by Vincy.

In this tutorial, we are going to see about how to merge two or more JSON string. This can be done by decoding given JSON objects and encoding after the merge.

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> 
<p>
<div>$json1 = <?php echo $json1; ?></div>
<div>$json2 = <?php echo $json2; ?></div>
</p>
<h4>Output:</h4> 
<div><?php echo $json_merge; ?></div>

Output

output

Download

↑ Back to Top

Share this Article