PHP JSON Array Merge

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

This PHP code tutorial was published on May 14, 2015.

↑ Back to Top