Home  >  Article  >  Backend Development  >  How to Merge JSON Objects in PHP?

How to Merge JSON Objects in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-06 11:57:02976browse

How to Merge JSON Objects in PHP?

Merging JSON Objects in PHP

When working with JSON data, there often arises a need to merge or combine multiple objects into a single cohesive entity. In PHP, this task can be accomplished through a series of steps:

1. Decoding the JSON:

The first step is to decode the JSON strings into PHP arrays using the json_decode() function. This function can take a second parameter true to associate keys to the arrays rather than treating them as objects.

2. Merging the Arrays:

Once the JSON strings have been decoded, the next step is to merge the arrays using the array_merge() function. This function combines the two arrays, replacing duplicate keys with the values from the second array.

3. Encoding the Result:

After merging the arrays, the final step is to encode the result back into a JSON string using the json_encode() function.

Example:

Consider the following two JSON strings:

JSON 1:

[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"}]

JSON 2:

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

To merge these two JSON strings and obtain a result that includes both the column name and default value, the following code can be used:

$json1 = '[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"}]';
$json2 = '[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},
{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]';

$decodedJson1 = json_decode($json1, true);
$decodedJson2 = json_decode($json2, true);

$mergedArray = array_merge($decodedJson1, $decodedJson2);

$mergedJson = json_encode($mergedArray);

The resulting $mergedJson variable will contain the following JSON string:

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

This demonstrates how to merge JSON objects in PHP and derive a merged JSON string that combines the data from the input JSONs.

The above is the detailed content of How to Merge JSON Objects 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