二维数组根据某列值归类

// 原数组:
 
[
    {
        "province": "河北省",
        "city": "石家庄市"
    },
    {
        "province": "河北省",
        "city": "衡水市"
    },
    {
        "province": "山西省",
        "city": "太原市"
    },
    {
        "province": "山西省",
        "city": "吕梁市"
    }
]

//期望数组: [ { "province": "河北省", "city": [ "石家庄市", "衡水市" ] }, { "province": "山西省", "city": [ "太原市", "吕梁市" ] } ]

  

 

Coding:

 

        $jsonStr = '[
                    {
                        "province": "河北省",
                        "city": "石家庄市"
                    },
                    {
                        "province": "河北省",
                        "city": "衡水市"
                    },
                    {
                        "province": "山西省",
                        "city": "太原市"
                    },
                    {
                        "province": "山西省",
                        "city": "吕梁市"
                    }
                   ]';
        $list = json_decode($jsonStr, true);
        $nList = [];
        foreach ($list as $val) {
            if (isset($nList[$val['province']])) {
                $nList[$val['province']]['city'][] = $val['city'];
            } else {
                $nList[$val['province']]['province'] = $val['province'];
                $nList[$val['province']]['city'][] = $val['city'];
            }
        }

        echo json_encode(array_values($nList));

 

上一篇:旅行商问题的近似算法之最近邻法(Nearest Neighbor) C语言实现


下一篇:Linux root 模式