PHP
Grouping Array Items by a Key
Learn an efficient way to group elements of a PHP array into sub-arrays based on the value of a specific common key, useful for categorization.
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'city' => 'New York'],
['id' => 2, 'name' => 'Bob', 'city' => 'London'],
['id' => 3, 'name' => 'Charlie', 'city' => 'New York'],
['id' => 4, 'name' => 'David', 'city' => 'Paris'],
['id' => 5, 'name' => 'Eve', 'city' => 'London'],
];
$groupedUsers = [];
foreach ($users as $user) {
$city = $user['city'];
if (!isset($groupedUsers[$city])) {
$groupedUsers[$city] = [];
}
$groupedUsers[$city][] = $user;
}
print_r($groupedUsers);
?>
How it works: This snippet provides a common pattern for grouping elements within an array based on a specific key's value. It iterates through the `$users` array, extracting the 'city' for each user. It then uses the 'city' as a key to build a new associative array, `$groupedUsers`, where each value is an array of users belonging to that city. This is highly useful for organizing data by categories.