如果我有兩個JSON,[ { "a" : "b" , "c" : "d" } ,{ "a" : "e" , "c" : "f"} ]
和{ "a" : "g" , "c" : "h"}
,是否有可能在php中合併並獲取以下數組?我怎麼能合併兩個JSON在PHP?
[ { "a" : "b" , "c" : "d" } ,{ "a" : "e" , "c" : "f"} ,{ "a" : "g" , "c" : "h"} ]
如果我有兩個JSON,[ { "a" : "b" , "c" : "d" } ,{ "a" : "e" , "c" : "f"} ]
和{ "a" : "g" , "c" : "h"}
,是否有可能在php中合併並獲取以下數組?我怎麼能合併兩個JSON在PHP?
[ { "a" : "b" , "c" : "d" } ,{ "a" : "e" , "c" : "f"} ,{ "a" : "g" , "c" : "h"} ]
您首先需要將解碼JSON對象:
$json1 = json_decode($data1, true);
$json2 = json_decode($data2, true);
然後合併數組:
$result = array_merge($json1,$json2);
和編碼回JSON:
$encodedResult = json_encode($result);
喜歡的東西json_encode()
應該可以工作,你可以對PHP官方文檔
PHP官方文檔json_decode
SE array_merge
試試這個:
<?php
$json1 = '[ { "a" : "b" , "c" : "d" }, { "a" : "e" , "c" : "f"} ]';
$json2 = '{ "a" : "g" , "c" : "h"}';
$json1 = json_decode($json1, true);
$json2 = json_decode($json2, true);
$final_array = array_merge($json1, $json2);
// Finally encode the result back to JSON.
$final_json = json_encode($final_array);
?>
忘記編碼合併陣列像OP問,但+1。 – Qix 2014-09-18 20:56:41
把握;轉換爲數組,添加新值,然後編碼回JSON。 – Qix 2014-09-18 17:52:58
絕對如此。 [你有什麼嘗試?](http://mattgemmell.com/what-have-you-tried/) – Ohgodwhy 2014-09-18 17:52:58
當然:'$ value1 [] = $ value2;'(假設你已經解析過JSON)。 – 2014-09-18 17:53:03