2014-09-18 31 views
-2

如果我有兩個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"} ] 
+0

把握;轉換爲數組,添加新值,然後編碼回JSON。 – Qix 2014-09-18 17:52:58

+1

絕對如此。 [你有什麼嘗試?](http://mattgemmell.com/what-have-you-tried/) – Ohgodwhy 2014-09-18 17:52:58

+0

當然:'$ value1 [] = $ value2;'(假設你已經解析過JSON)。 – 2014-09-18 17:53:03

回答

-1

您首先需要將解碼JSON對象:

$json1 = json_decode($data1, true); 
$json2 = json_decode($data2, true); 

然後合併數組:

$result = array_merge($json1,$json2); 

和編碼回JSON:

$encodedResult = json_encode($result); 
+0

咦?不,JSON不是可以在PHP中合併的對象。 JSON是一種序列化格式。 – Qix 2014-09-18 17:54:52

+0

我假設他已將JSON解碼爲數組... – qbit 2014-09-18 17:56:02

+0

他們從來沒有這麼說過。他們說他們有兩件JSON。 – Qix 2014-09-18 17:56:32

0

喜歡的東西json_encode()應該可以工作,你可以對PHP官方文檔

1

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); 
?> 
+0

忘記編碼合併陣列像OP問,但+1。 – Qix 2014-09-18 20:56:41