PHP
Group Associative Array Elements by a Specific Key
Learn how to efficiently group elements in an associative array based on a common key's value, useful for organizing data by categories or IDs.
function group_by_key(array $array, string $key): array {
$result = [];
foreach ($array as $item) {
if (isset($item[$key])) {
$result[$item[$key]][] = $item;
}
}
return $result;
}
$products = [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics'],
['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics'],
['id' => 3, 'name' => 'Keyboard', 'category' => 'Electronics'],
['id' => 4, 'name' => 'T-Shirt', 'category' => 'Apparel'],
['id' => 5, 'name' => 'Jeans', 'category' => 'Apparel'],
];
$groupedProducts = group_by_key($products, 'category');
// var_dump($groupedProducts);
/*
array(2) {
["Electronics"]=> array(3) { ... }
["Apparel"]=> array(2) { ... }
}
*/
How it works: This snippet provides a `group_by_key` function to reorganize an array of associative arrays. It iterates through the input array, using the value of a specified `$key` to create new top-level keys in the result array. Each item from the original array is then appended to the sub-array corresponding to its grouped key, making it easy to access related items for reports or structured display.