为了账号安全,请及时绑定邮箱和手机立即绑定

php输出指定结构

php输出指定结构

PHP
蝴蝶不菲 2019-03-12 13:48:11
我查询数据库出来有一个结构 [ { "id": 1, "price": { "flowOutPlanPrice": { "national": null, "inProvince": { "isDaily": 0, "price": "1.00", "quantity": "0.50" } } } }, { "id": 1, "price": { "flowOutPlanPrice": { "national": { "isDaily": 0, "price": "2.00", "quantity": "0.50" }, "inProvince": null } } }, { "id": 2, "price": { "flowOutPlanPrice": { "national": { "isDaily": 0, "price": "2.00", "quantity": "0.50" }, "inProvince": null } } }, { "id": 2, "price": { "flowOutPlanPrice": { "national": null, "inProvince": { "isDaily": 0, "price": "1.00", "quantity": "0.50" } } } } ] 然后怎么处理输出下面的解构啊?相同id的,national和inProvince合并一起 [ { "id": 1, "price": { "flowOutPlanPrice": { "national": { "isDaily": 0, "price": "2.00", "quantity": "0.50" }, "inProvince": { "isDaily": 0, "price": "1.00", "quantity": "0.50" } } } }, { "id": 2, "price": { "flowOutPlanPrice": { "national": { "isDaily": 0, "price": "2.00", "quantity": "0.50" }, "inProvince": { "isDaily": 0, "price": "1.00", "quantity": "0.50" } } } } ]
查看完整描述

1 回答

?
森栏

TA贡献1810条经验 获得超5个赞

$arr = [];
foreach ($data as $price) {
    if (! isset($arr[$price['id']])) {
        $arr[$price['id']] = $price;
    }
    $inProvince = $price['price']['flowOutPlanPrice']['inProvince'];

    if ($arr[$price['id']]['price']['flowOutPlanPrice']['national'] === null) {
        $arr[$price['id']]['price']['flowOutPlanPrice']['national'] = $price['price']['flowOutPlanPrice']['national'];
    }

    if ($arr[$price['id']]['price']['flowOutPlanPrice']['inProvince'] === null) {
        $arr[$price['id']]['price']['flowOutPlanPrice']['inProvince'] = $price['price']['flowOutPlanPrice']['inProvince'];
    }
}
$arr = array_values($arr);
$data 就是你的数据 最后都放在了 $arr 中
查看完整回答
反对 回复 2019-03-18
  • 1 回答
  • 0 关注
  • 441 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信