2017-05-02 45 views
0

下面是我的這些JSON字符串,我試圖添加jsons。我如何實現。如何我可以合併兩個以上的Json字符串在PHP

$json1 = {"properties":{"title":"test","labels":["JanActual","Jan","Goal"],"values":["0","10000","0"]}} 
$json2 = {"key":"Rental","type":"bar","values":["0","10000","0"]} 
$json3 = {"key":"Service","type":"bar","values":["189","30000","0"]} 

我想用它來合併它們和我期待輸出像下面

{ 
    "properties":{ 
     "title":"test", 
     "labels":[ 
      "JanActual", 
      "Jan", 
      "Goal" 
     ], 
     "values":[ 
      "0", 
      "10000", 
      "0" 
     ] 
    }, 
    "data": [ 
     { 
      "key":"Rental", 
      "type":"bar", 
      "values":[ 
      "0", 
      "10000", 
      "0" 
      ] 
     }, 
     { 
      "key":"Service", 
      "type":"bar", 
      "values":[ 
       "189", 
       "30000", 
       "0" 
      ] 
     } 
    ] 
} 

任何幫助嗎?

+0

http://stackoverflow.com/questions/37174076/how-can-i-merge-two-json-strings-in-php –

回答

4

解碼JSON到PHP陣列,合併和編碼背面

$json1 = json_decode($json1, true); 
$json1['data'] = array(
    json_decode($json2, true), 
    json_decode($json3, true) 
); 

echo json_encode($json1); 
+0

很好的答案,但我認爲當從兩個或更多json集合合時,你還必須檢查是否覆蓋key->值。 – twg

+0

@twg你是什麼意思?我無法想象什麼可以覆蓋,因爲每個json對象都將數組的元素與數字索引分開 – splash58

相關問題