php输出指定结构

我查询数据库出来有一个结构

[
    {
        "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.4k
1 个回答
$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 中
推荐问题
宣传栏