PHP
Group an Array of Arrays by a Specific Key's Value
Organize and categorize a list of associative arrays by grouping them into a new structure based on the value of a designated key in PHP.
<?php
$products = [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
['id' => 2, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
['id' => 3, 'name' => 'Desk Chair', 'category' => 'Furniture', 'price' => 300],
['id' => 4, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25],
['id' => 5, 'name' => 'Dining Table', 'category' => 'Furniture', 'price' => 800],
];
$groupedProducts = [];
foreach ($products as $product) {
$category = $product['category'];
if (!isset($groupedProducts[$category])) {
$groupedProducts[$category] = [];
}
$groupedProducts[$category][] = $product;
}
print_r($groupedProducts);
/*
Output:
Array
(
[Electronics] => Array
(
[0] => Array
(
[id] => 1
[name] => Laptop
[category] => Electronics
[price] => 1200
)
[1] => Array
(
[id] => 2
[name] => Keyboard
[category] => Electronics
[price] => 75
)
[2] => Array
(
[id] => 4
[name] => Mouse
[category] => Electronics
[price] => 25
)
)
[Furniture] => Array
(
[0] => Array
(
[id] => 3
[name] => Desk Chair
[category] => Furniture
[price] => 300
)
[1] => Array
(
[id] => 5
[name] => Dining Table
[category] => Furniture
[price] => 800
)
)
)
*/
How it works: This snippet demonstrates how to group a list of associative arrays based on the value of a specific key (in this case, 'category'). It iterates through the original array, and for each item, it uses the designated key's value to create a new key in the `$groupedProducts` array. If the key doesn't exist, it's initialized as an empty array before the current item is appended to it. This technique is extremely useful for organizing data for display or further processing.