在PHP中合并两个json

时间:2013-11-29 12:47:12

标签: php json merge

我有两个json的

第一个是

    [{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"}
,{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}]

第二个是

[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},
{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]

我想合并它们并拥有像

这样的json
[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number","DEFAULT_VALUE":"1521"}
,{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number","DEFAULT_VALUEE":"C1435"}]

有没有办法合并它们?如果需要更改JSON的结构,我也可以

感谢。

4 个答案:

答案 0 :(得分:33)

json_encode(array_merge(json_decode($a, true),json_decode($b, true)))之类的东西应该有用。

官方PHP文档中的

array_merge

官方PHP文档中的

json_decode

编辑:尝试将true作为第二个参数添加到json_decode。那会把对象转换成关联数组。

编辑2 :尝试array-merge-recursive并在下方查看我的评论。抱歉,现在必须退出:( 这看起来像一个完整正确的解决方案:https://stackoverflow.com/a/20286594/1466341

答案 1 :(得分:6)

管理将这些放在一起。最有可能是一个更好的解决方案,但这是我最接近的。

$a = '[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"},{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}]';
$b = '[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]';
$r = [];
foreach(json_decode($a, true) as $key => $array){
 $r[$key] = array_merge(json_decode($b, true)[$key],$array);
}
echo json_encode($r);

返回,

[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521","COLUMN_TITLE":"Order Number"},
{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435","COLUMN_TITLE":"Customer Number"}]

答案 2 :(得分:2)

这对我来说就像是一种魅力

json_encode(array_merge(json_decode($a, true),json_decode($b, true)))

这是一个完整的例子

$query="SELECT * FROM `customer` where patient_id='1111118'";

$mysql_result = mysql_query($query);

$rows = array();
while($r = mysql_fetch_assoc($mysql_result)) {
    $rows[] = $r;
}
$json_personal_information=json_encode($rows);
//echo $json_personal_information;




$query="SELECT * FROM `doctor` where patient_id='1111118'";

$mysql_result = mysql_query($query);

$rows = array();
while($r = mysql_fetch_assoc($mysql_result)) {
    $rows[] = $r;
}
$json_doctor_information=json_encode($rows);
//echo $json_doctor_information;

echo $merger=json_encode(array_merge(json_decode($json_personal_information, true),json_decode($json_doctor_information, true)));

答案 3 :(得分:0)

这对我有用! $ dados1 = json_encode(arrray('data'=>'1')); $ dados2 = json_encode(arrray('data2'=>'2'));回声json_encode(array_merge(json_decode($ dados1,true),json_decode($ dados2,true)));