PHP
Group Array Elements by Key Value
Learn how to efficiently group an array of associative arrays or objects based on the value of a specific key, creating categorized data structures.
$users = [
['id' => 1, 'name' => 'Alice', 'country' => 'USA'],
['id' => 2, 'name' => 'Bob', 'country' => 'Canada'],
['id' => 3, 'name' => 'Charlie', 'country' => 'USA'],
['id' => 4, 'name' => 'David', 'country' => 'UK'],
['id' => 5, 'name' => 'Eve', 'country' => 'Canada'],
];
$groupedByCountry = [];
foreach ($users as $user) {
$country = $user['country'];
if (!isset($groupedByCountry[$country])) {
$groupedByCountry[$country] = [];
}
$groupedByCountry[$country][] = $user;
}
print_r($groupedByCountry);
How it works: This snippet demonstrates how to group elements of an array based on the value of a specific key (in this case, 'country'). It iterates through the original array and uses the value of the chosen key as the new primary key for the `groupedByCountry` array. Each entry under the country key then becomes an array containing all original elements that share that country value. This is extremely useful for organizing data for display or further processing.