Home > Backend Development > PHP Tutorial > 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
Release: 2024-11-06 12:02:02
Original
1063 people have browsed it

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"}
]
Copy after login

Second JSON String:

[
  {"COLUMN_NAME": "ORDER_NO", "DEFAULT_VALUE": "1521"},
  {"COLUMN_NAME": "CUSTOMER_NO", "DEFAULT_VALUEE": "C1435"}
]
Copy after login

Desired Output:

[
  {"COLUMN_NAME": "ORDER_NO", "COLUMN_TITLE": "Order Number", "DEFAULT_VALUE": "1521"},
  {"COLUMN_NAME": "CUSTOMER_NO", "COLUMN_TITLE": "Customer Number", "DEFAULT_VALUEE": "C1435"}
]
Copy after login
Copy after login

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;
Copy after login

Output:

[
  {"COLUMN_NAME": "ORDER_NO", "COLUMN_TITLE": "Order Number", "DEFAULT_VALUE": "1521"},
  {"COLUMN_NAME": "CUSTOMER_NO", "COLUMN_TITLE": "Customer Number", "DEFAULT_VALUEE": "C1435"}
]
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template