我怎么能在PHP中合并两个json?

时间:2014-09-18 17:51:03

标签: php arrays json

如果我有两个JSON,[ { "a" : "b" , "c" : "d" } ,{ "a" : "e" , "c" : "f"} ]{ "a" : "g" , "c" : "h"},是否可以在php中合并并获取以下数组?

[ { "a" : "b" , "c" : "d" } ,{ "a" : "e" , "c" : "f"} ,{ "a" : "g" , "c" : "h"} ]  

3 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

json_encode()这样的东西应该可行,你可以在官方PHP文档array_merge上使用json_decode

答案 2 :(得分:-1)

首先需要解码JSON对象:

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

然后合并数组:

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

并编码回JSON:

$encodedResult = json_encode($result);