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