PHP

Grouping PHP Associative Arrays by a Specific Key

Learn how to efficiently group a list of associative arrays or objects by the value of a common key, creating a structured, categorized dataset.

<?php

$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' => 60],
    ['id' => 6, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 300],
];

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

print_r($groupedProducts);

// Expected Output Structure:
// Array
// (
//     [Electronics] => Array (...)
//     [Apparel] => Array (...)
// )
// Each sub-array contains products belonging to that category.
How it works: This snippet demonstrates how to group an array of items (each being an associative array or object) based on the value of a specific key. It iterates through the original array, uses the value of the designated key (e.g., 'category') as the new outer array key, and then appends the current item to the corresponding nested array.

Need help integrating this into your project?

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

Hire DigitalCodeLabs