elize elize - 5 months ago 70
PHP Question

How can I merge two JSON strings in PHP?

I have two JSON strings like these:

$json1 = '[ {"src":"1","order":"2"}, {"src":"10","order":"20"}, ... ]';


$json2 = '[ {"src":"4","order":"5"}, {"src":"6","order":"7"}, ... ]';

I am trying to use this to merge them:

$images = array_merge(json_decode($json1 ),json_decode($json2));

$json = '[';
$comma = null;
foreach($images as $image)
$comma = ',';
$json .= $comma.'{"src":"'.$image['src'].'","order":"'.$image['order'].'"}';
$json .= ']';
echo $json;

but I am getting this error:

ERROR: can not use object type of stdCLASS..

What am I doing wrong?


When you're calling json_decode, you're decoding it as an object. If you want it to be an array, you have to do

$images =  array_merge(json_decode($json1, true),json_decode($json2, true));

For more information about json_decode: