PHP
Group Associative Array Items by a Common Key
Organize a PHP array of associative arrays by grouping items based on a shared key's value, creating a nested structure for easier data access and processing.
<?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' => 250],
['id' => 4, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 300],
['id' => 5, 'name' => 'Table Lamp', 'category' => 'Furniture', 'price' => 50]
];
$groupedProducts = [];
foreach ($products as $product) {
$category = $product['category'];
if (!isset($groupedProducts[$category])) {
$groupedProducts[$category] = [];
}
$groupedProducts[$category][] = $product;
}
print_r($groupedProducts);
/* Expected 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] => Monitor [category] => Electronics [price] => 300 )
)
[Furniture] => Array
(
[0] => Array ( [id] => 3 [name] => Desk Chair [category] => Furniture [price] => 250 )
[1] => Array ( [id] => 5 [name] => Table Lamp [category] => Furniture [price] => 50 )
)
)
*/
?>
How it works: This snippet demonstrates a common pattern for grouping associative array elements based on the value of a specific key. It iterates through the original array, using the specified key's value (e.g., 'category') as the key for a new, nested array. This creates a structured output where all items sharing that common key are grouped together, facilitating organized data access.