Home  >  Article  >  Backend Development  >  How do you merge multiple JSON strings in PHP?

How do you merge multiple JSON strings in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-06 07:58:02387browse

How do you merge multiple JSON strings in PHP?

Merging Multiple JSON Strings in PHP

Combining multiple JSON strings can be necessary when working with data from different sources or performing complex data manipulations. In PHP, there are several approaches for merging JSON strings.

Method 1: json_encode() and array_merge()

One common approach is to use the json_decode() function to convert the JSON strings to PHP arrays. You can then use the array_merge() function to combine the arrays and retain the key-value pairs from each JSON string. Finally, 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);

Method 2: array_merge_recursive()

If you need to merge JSON strings that contain nested structures, you can use array_merge_recursive() instead of array_merge(). This function will recursively merge arrays, including nested arrays and objects.

$json1 = '{
  "records": [
    {"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"},
    {"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}
  ]
}';

$json2 = '{
  "records": [
    {"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_recursive($array1, $array2);
$mergedJSON = json_encode($mergedArray);

By using these techniques, you can efficiently merge JSON strings in PHP and manipulate data from multiple sources.

The above is the detailed content of How do you merge multiple JSON strings in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn