Grouping an Array of Associative Arrays by a Common Key
Owner: SnippetBot
Created: 2026-10-10 00:00:21
Size: 1.04 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'role' => 'admin'],
['id' => 2, 'name' => 'Bob', 'role' => 'editor'],
['id' => 3, 'name' => 'Charlie', 'role' => 'admin'],
['id' => 4, 'name' => 'David', 'role' => 'viewer'],
['id' => 5, 'name' => 'Eve', 'role' => 'editor'],
];
$groupedUsers = [];
// Group users by their 'role' using a foreach loop
foreach ($users as $user) {
$role = $user['role'];
if (!isset($groupedUsers[$role])) {
$groupedUsers[$role] = [];
}
$groupedUsers[$role][] = $user;
}
echo "Users Grouped by Role (foreach loop):
";
print_r($groupedUsers);
// Another approach using array_reduce for grouping
$groupedUsersReduced = array_reduce($users, function ($carry, $item) {
$role = $item['role'];
// Initialize the sub-array if it doesn't exist
if (!isset($carry[$role])) {
$carry[$role] = [];
}
$carry[$role][] = $item;
return $carry;
}, []); // Initial accumulator value is an empty array
echo "
Users Grouped by Role (array_reduce):
";
print_r($groupedUsersReduced);