PHP
Grouping Associative Arrays by a Common Key
Learn to efficiently group a list of associative arrays or objects in PHP by a specific key, useful for categorizing data.
<?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'],
];
$usersByRole = [];
foreach ($users as $user) {
$role = $user['role'];
if (!isset($usersByRole[$role])) {
$usersByRole[$role] = [];
}
$usersByRole[$role][] = $user;
}
print_r($usersByRole);
?>
How it works: This snippet demonstrates how to group a flat list of associative arrays into a nested array, where the outer keys are derived from a common attribute (e.g., 'role'). It iterates through the original array, creating new keys in the result array as needed and appending the current element to the corresponding group, effectively categorizing the data.