PHP
How to Group an Array of Associative Arrays by a Specific Key in PHP
Efficiently reorganize and group data within an array of associative arrays by a common key, creating a structured nested array for easier access and manipulation.
<?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'],
];
$groupedByCity = [];
foreach ($users as $user) {
$city = $user['city'];
if (!isset($groupedByCity[$city])) {
$groupedByCity[$city] = [];
}
$groupedByCity[$city][] = $user;
}
print_r($groupedByCity);
/*
Expected Output:
Array
(
[New York] => Array
(
[0] => Array
(
[id] => 1
[name] => Alice
[city] => New York
)
[1] => Array
(
[id] => 3
[name] => Charlie
[city] => New York
)
)
[London] => Array
(
[0] => Array
(
[id] => 2
[name] => Bob
[city] => London
)
[1] => Array
(
[id] => 5
[name] => Eve
[city] => London
)
)
[Paris] => Array
(
[0] => Array
(
[id] => 4
[name] => David
[city] => Paris
)
)
)
*/
?>
How it works: This code snippet demonstrates how to group an array of associative arrays based on the value of a specific key (in this case, 'city'). It iterates through the original array and uses the chosen key's value to create new keys in a new array, where each new key holds an array of all matching items. This is a common pattern for organizing data for display or further processing.