其他分享
首页 > 其他分享> > 二维数组根据某列值归类

二维数组根据某列值归类

作者:互联网

// 原数组:
 
[
    {
        "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));

 

标签:province,city,山西省,val,河北省,某列值,归类,二维,nList
来源: https://www.cnblogs.com/afeige/p/14859130.html