Fed Fed - 19 days ago 8
PHP Question

Cannot merge two JSON objects in PHP, the result is null

I want to add a json object to other json object in PHP, I tried this and many other methods, but I cannot find the correct method

This is What I have:

$js_string1 = "{\"info\":[{\"thumb\":\"\",\"count\":1,\"date\":\"11/11/2016 4:05:28\",\"categories\":[null,null,null,null,null],\"sharing\":\"\",\"status\":\"private\",\"title\":\"Apple\",\"windows\":[{\"alwaysOnTop\":false,\"focused\":true,\"width\":1440,\"windowId\":825},{\"active\":false,\"audible\":false, \"height\":727,\"width\":1440,\"windowId\":825}],\"top\":26,\"type\":\"normal\",\"width\":1440}]}]}";

$js_string2 = "{\"thumb\":\"\",\"count\":1,\"date\":\"10/10/2010 5:07:30\",\"categories\":[null,null,null,null,null],\"sharing\":\"\",\"status\":\"private\",\"title\":\"Some Title\",\"windows\":[{\"alwaysOnTop\":false,\"focused\":true,\"width\":1024,\"windowId\":201},{\"active\":false,\"audible\":false, \"height\":500,\"width\":1024,\"windowId\":301}],\"top\":26,\"type\":\"normal\",\"width\":1024}]}";

$result = json_encode(array_merge(json_decode($js_string1, true),json_decode($js_string2, true)));


Expected result is:

{"info":[{"thumb":"","count":1,"date":"11/11/2016 4:05:28","categories":[null,null,null,null,null],"sharing":"","status":"private","title":"Apple","windows":[{"alwaysOnTop":false,"focused":true,"width":1440,"windowId":825},{"active":false,"audible":false, "height":727,"width":1440,"windowId":825}],"top":26,"type":"normal","width":1440}] }, {"thumb":"","count":1,"date":"10/10/2010 5:07:30","categories":[null,null,null,null,null],"sharing":"","status":"private","title":"Some Title","windows":[{"alwaysOnTop":false,"focused":true,"width":1024,"windowId":201},{"active":false,"audible":false, "height":500,"width":1024,"windowId":301}],"top":26,"type":"normal","width":1024}]} ]}


May somebody explain and show me how to do this correctly? because I tried many different ways and I cannot find how to do this correctly.

What I want to do is just to add $js_string2 to $js_string1 and keep same structure for $js_string1, something like:

{"info":[ { .... }, { $js_string2 } ]}

Answer

Your code is fine, both JSON strings are not. They both have an additional "]}" at the end.

Executing your code raises a warning array_merge(): Argument #1 is not an array. That should have let you to the cause.

Comments