鍍金池/ 問答/PHP/ php輸出指定結(jié)構(gòu)

php輸出指定結(jié)構(gòu)

我查詢數(shù)據(jù)庫出來有一個(gè)結(jié)構(gòu)

[
    {
        "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"
                }
            }
        }
    }
]

然后怎么處理輸出下面的解構(gòu)?。肯嗤琲d的,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"
                }
            }
        }
    }
]
回答
編輯回答
朽鹿
$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 就是你的數(shù)據(jù) 最后都放在了 $arr 中
2018年2月21日 03:11