Home  >  Article  >  Backend Development  >  How can I merge multiple JSON objects in PHP?

How can I merge multiple JSON objects in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-06 09:36:02504browse

How can I merge multiple JSON objects in PHP?

Merging Multiple JSON Objects in PHP

Combining multiple JSON objects can be a common task in web development. In this case, you have two JSON objects and want to merge them into a single object.

To do this, you can use the array_merge function in PHP. This function takes two or more arrays as arguments and returns a new array that contains all the elements from each argument array.

In your case, you can convert your JSON objects to arrays using the json_decode function, which takes a JSON string as an argument and returns an array.

Here's an example of how you can merge your two JSON objects using array_merge and json_decode:

$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;

This code will output the following JSON object:

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

Which is exactly the output you were looking for.

The above is the detailed content of How can I merge multiple 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