PHP
Grouping Associative Arrays by a Key
Learn how to efficiently group an array of associative arrays or objects by a specific key's value in PHP, useful for organizing related data for display or processing.
<?php
function groupArrayByField(array $array, string $field): array
{
$grouped = [];
foreach ($array as $item) {
if (is_array($item) && isset($item[$field])) {
$grouped[$item[$field]][] = $item;
} elseif (is_object($item) && isset($item->$field)) {
$grouped[$item->$field][] = $item;
}
}
return $grouped;
}
$products = [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25],
['id' => 3, 'name' => 'Keyboard', 'category' => 'Peripherals', 'price' => 75],
['id' => 4, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 300],
['id' => 5, 'name' => 'Webcam', 'category' => 'Peripherals', 'price' => 50],
];
$groupedByCategory = groupArrayByField($products, 'category');
/*
Output:
[
'Electronics' => [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25],
['id' => 4, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 300],
],
'Peripherals' => [
['id' => 3, 'name' => 'Keyboard', 'category' => 'Peripherals', 'price' => 75],
['id' => 5, 'name' => 'Webcam', 'category' => 'Peripherals', 'price' => 50],
],
]
*/
print_r($groupedByCategory);
How it works: This snippet provides a flexible function to group an array of associative arrays or objects by a specified field. It iterates through the input array, using the value of the designated field as the key for the new grouped array, collecting all matching items under that key.