$arr = [
0 => [
'name' => 'Воронеж',
'key' => 'city',
'id' => 35
],
1 => [
'name' => 'Ленинский район',
'key' => 'region',
'id' => 39
],
2 => [
'name' => 'Центральный район',
'key' => 'region',
'id' => 44
],
3 => [
'name' => 'Воронеж',
'key' => 'city',
'id' => 51
],
4 => [
'name' => 'Воронеж',
'key' => 'city',
'id' => 79
],
5 => [
'name' => 'Ленинский район',
'key' => 'region',
'id' => 112
],
]
$region = [
0 => [
'name' => 'Ленинский район',
'ids' => '39,112'
],
1 => [
'name' => 'Центральный район',
'ids' => '44'
]
]
$city = [
0 => [
'name' => 'Воронеж',
'ids' => '35,51,79'
]
]
$grouped = [];
foreach ($arr as [ 'id' => $id, 'name' => $name, 'key' => $key ]) {
$grouped[$key][$name] ??= [ 'name' => $name, 'ids' => [] ];
$grouped[$key][$name]['ids'][] = $id;
}
foreach ($keys as $k) {
$$k = array_map(fn($n) => [
'name' => $n['name'],
'ids' => implode(', ', $n['ids'])
], array_values($grouped[$k] ?? []));
}