Home > Article > Backend Development > How to Merge Two JSON Strings in PHP to Create a Single Combined JSON String?
Question:
Given two JSON strings representing a list of column names and titles for a database table, how can we merge them to create a single JSON string that includes both sets of information?
First JSON String:
[ {"COLUMN_NAME": "ORDER_NO", "COLUMN_TITLE": "Order Number"}, {"COLUMN_NAME": "CUSTOMER_NO", "COLUMN_TITLE": "Customer Number"} ]
Second JSON String:
[ {"COLUMN_NAME": "ORDER_NO", "DEFAULT_VALUE": "1521"}, {"COLUMN_NAME": "CUSTOMER_NO", "DEFAULT_VALUEE": "C1435"} ]
Desired Output:
[ {"COLUMN_NAME": "ORDER_NO", "COLUMN_TITLE": "Order Number", "DEFAULT_VALUE": "1521"}, {"COLUMN_NAME": "CUSTOMER_NO", "COLUMN_TITLE": "Customer Number", "DEFAULT_VALUEE": "C1435"} ]
Solution:
To merge the two JSON strings, we can use the array_merge and json_decode functions. json_decode converts the JSON strings into PHP arrays. array_merge combines these arrays, and we can then use json_encode to convert the merged array back to a JSON string.
$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); $mergedArray = array_merge($array1, $array2); $mergedJson = json_encode($mergedArray); echo $mergedJson;
Output:
[ {"COLUMN_NAME": "ORDER_NO", "COLUMN_TITLE": "Order Number", "DEFAULT_VALUE": "1521"}, {"COLUMN_NAME": "CUSTOMER_NO", "COLUMN_TITLE": "Customer Number", "DEFAULT_VALUEE": "C1435"} ]
The above is the detailed content of How to Merge Two JSON Strings in PHP to Create a Single Combined JSON String?. For more information, please follow other related articles on the PHP Chinese website!