PHP
Group Associative Arrays by Common Key Value
Learn to group an array of associative arrays into nested arrays based on a common key's value, effectively organizing and structuring data in PHP.
$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 SQL'],
];
$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 [category] => Electronics [name] => Laptop )
[1] => Array ( [id] => 3 [category] => Electronics [name] => Smartphone )
)
[Books] => Array
(
[0] => Array ( [id] => 2 [category] => Books [name] => PHP Basics )
[1] => Array ( [id] => 4 [category] => Books [name] => Advanced SQL )
)
)*/
How it works: This snippet demonstrates how to group an array of associative arrays based on the value of a specific key (e.g., 'category'). It iterates through the original array, using the specified key's value to create a new key in the `groupedProducts` array. Each item sharing the same key value is then added to a nested array under that key, creating a structured, grouped dataset.