如何在php中合并两个json


how could i merge two json in php?

如果我有两个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"} ]  

试试这个:

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

类似json_encode()的东西应该可以工作,您可以在官方PHP文档上使用array_merge,在官方PHP文件上使用json_decode

您首先需要解码JSON对象:

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

然后合并阵列:

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

并编码回JSON:

$encodedResult = json_encode($result);