PHP
Group an Array of Associative Arrays by a Specific Key
Learn how to efficiently group elements in an array of associative arrays based on the value of a specific key, organizing your data for easier access.
function groupArrayBy(array $array, string $key): array
{
$grouped = [];
foreach ($array as $item) {
if (isset($item[$key])) {
$grouped[$item[$key]][] = $item;
}
}
return $grouped;
}
$products = [
['id' => 1, 'category' => 'Electronics', 'name' => 'Laptop'],
['id' => 2, 'category' => 'Books', 'name' => 'PHP Basics'],
['id' => 3, 'category' => 'Electronics', 'name' => 'Smartphone'],
['id' => 4, 'category' => 'Books', 'name' => 'Advanced Algorithms'],
];
$groupedProducts = groupArrayBy($products, 'category');
// var_dump($groupedProducts);
/* Expected Output:
[
"Electronics" => [
["id" => 1, "category" => "Electronics", "name" => "Laptop"],
["id" => 3, "category" => "Electronics", "name" => "Smartphone"]
],
"Books" => [
["id" => 2, "category" => "Books", "name" => "PHP Basics"],
["id" => 4, "category" => "Books", "name" => "Advanced Algorithms"]
]
]
*/
How it works: This function `groupArrayBy` takes an array of associative arrays and a key name. It iterates through the input array, using the value of the specified key from each item as the new primary key in the `$grouped` array. Each item is then added as an element to the array corresponding to its category, effectively grouping all related items together.