PHP

Group Associative Arrays by a Key's Value

Learn how to efficiently group a list of associative arrays or objects in PHP into sub-arrays based on the common value of a specified key.

$products = [
    ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
    ['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25],
    ['id' => 3, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
    ['id' => 4, 'name' => 'T-Shirt', 'category' => 'Apparel', 'price' => 20],
    ['id' => 5, 'name' => 'Jeans', 'category' => 'Apparel', 'price' => 50],
];

$groupedProducts = [];
foreach ($products as $product) {
    $category = $product['category'];
    if (!isset($groupedProducts[$category])) {
        $groupedProducts[$category] = [];
    }
    $groupedProducts[$category][] = $product;
}

// Using array_reduce for a more functional approach (PHP 5.3+)
$groupedProductsFunctional = array_reduce($products, function ($carry, $item) {
    $category = $item['category'];
    $carry[$category][] = $item;
    return $carry;
}, []);

print_r($groupedProducts);
print_r($groupedProductsFunctional);
How it works: This snippet demonstrates two methods to group an array of associative arrays by the value of a specific key (e.g., 'category'). The first uses a `foreach` loop to iterate and build the new grouped array. The second, more functional approach, leverages `array_reduce` to achieve the same result in a more concise manner, which is often preferred for readability in certain contexts. Both methods create a new associative array where keys are the grouping values and values are arrays of the original items belonging to that group.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs