sanders sanders - 5 months ago 8
JSON Question

Merging json encoded arrays

Lets say I have these arrays:

$array1 = [
'test' => json_encode([
'key1' => 'val1',
'key2' => 'val2',
'key3' => 'val3'
])
]


Now I have another array

$array2 = [
'test' => json_encode([
'key4' => 'val4'
])
]


After merge I want it to look like :

$array3 = [
'test' => json_encode([
'key1' => 'val1',
'key2' => 'val2',
'key3' => 'val3',
'key4' => 'val4',
])
]


But when I do
$result = array_merge($array1, $array2)


Then I get this:

$array3 = [
'test' => json_encode([
'key4' => 'val4'
])
]


Any suggestions how to fix this? I tried it with
array_merge_recursive
but that also does not give the right result.

Thanks.

Answer

I fixed this to by putting the test key in it's own variable. Then I merged them and json_encoded it.

Comments