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

How to Merge Multiple JSON Objects in PHP?

Patricia Arquette
Release: 2024-11-08 16:35:02
Original
373 people have browsed it

How to Merge Multiple JSON Objects in PHP?

Merging Multiple JSON Objects in PHP

In PHP, merging two or more JSON objects can be achieved using the array_merge() function. This function takes an array of arrays as input and combines their values into a single array.

To merge two JSON objects, we first need to convert them into PHP arrays using the json_decode() function. Here's an example:

<?php

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

// Merge the two arrays
$merged_array = array_merge($array1, $array2);

// Encode the merged array back into JSON
$merged_json = json_encode($merged_array);

echo $merged_json;
Copy after login

The above code will produce the following JSON 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

Note that the output JSON has a slightly different structure compared to the desired one. This is because the array_merge() function only combines the array values, and it does not retain the original keys. To preserve the original keys, we can use the array_merge_recursive() function instead.

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