Merging two json in PHP

Something like this should work:

json_encode(
    array_merge(
        json_decode($a, true),
        json_decode($b, true)
    )
)

or the same as one-liner:

json_encode(array_merge(json_decode($a, true),json_decode($b, true)))

array_merge in official PHP documentation

json_decode in official PHP documentation

EDIT: try adding true as second parameter to json_decode. That'll convert objects to associative arrays.

EDIT 2: try array-merge-recursive and see my comment below. Sorry have to log out now :( This looks like a full correct solution: https://stackoverflow.com/a/20286594/1466341


Managed to throw this together. There is most likely a better solution, but this is the closest I got.

$a = '[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"},{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}]';
$b = '[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]';
$r = [];
foreach(json_decode($a, true) as $key => $array){
 $r[$key] = array_merge(json_decode($b, true)[$key],$array);
}
echo json_encode($r);

returns,

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

Tags:

Php

Json

Merge