Home > Article > Backend Development > How to Merge Multiple JSON Objects in PHP?
Merging Multiple JSON Objects in PHP
In PHP, merging two or more JSON objects can be achieved using the array_merge() function. This function takes an array of arrays as input and combines their values into a single array.
To merge two JSON objects, we first need to convert them into PHP arrays using the json_decode() function. Here's an example:
<?php $json1 = '[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"},{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}]'; $json2 = '[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]'; $array1 = json_decode($json1, true); $array2 = json_decode($json2, true); // Merge the two arrays $merged_array = array_merge($array1, $array2); // Encode the merged array back into JSON $merged_json = json_encode($merged_array); echo $merged_json;
The above code will produce the following JSON output:
[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number","DEFAULT_VALUE":"1521"},{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number","DEFAULT_VALUEE":"C1435"}]
Note that the output JSON has a slightly different structure compared to the desired one. This is because the array_merge() function only combines the array values, and it does not retain the original keys. To preserve the original keys, we can use the array_merge_recursive() function instead.
The above is the detailed content of How to Merge Multiple JSON Objects in PHP?. For more information, please follow other related articles on the PHP Chinese website!