Home >Backend Development >PHP Tutorial >数组 相同键值合并问题
下面格式的数组,需要合并相同clientId的roleId。
$data = '[ { "ClientId": 0, "RoleId": 2 }, { "ClientId": 1, "RoleId": 1 }, { "ClientId": 1, "RoleId": 4 } ]';$data = json_decode($data);
$data = '[ { "ClientId": 0, "RoleId": [2] }, { "ClientId": 1, "RoleId": [1,4] } ]';$data = json_decode($data);
$data = json_decode($data, true);$arr = array();foreach($data as $itm) { $arr[$itm['ClientId']]['ClientId'] = $itm['ClientId']; $arr[$itm['ClientId']]['RoleId'][] = $itm['RoleId'];}$arr = array_values($arr);