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);