Home  >  Article  >  Backend Development  >  How to Merge Two JSON Strings in PHP to Create a Single Combined JSON String?

How to Merge Two JSON Strings in PHP to Create a Single Combined JSON String?

Susan Sarandon
Susan SarandonOriginal
2024-11-06 12:02:02900browse

How to Merge Two JSON Strings in PHP to Create a Single Combined JSON String?

Merging Two JSON Strings in PHP

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!

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