← Back to all snippets
PHP

Group Associative Arrays by a Common Key

Organize and group an array of associative arrays based on a specified key's value in PHP, creating structured data suitable for reporting or display purposes.

<?php
$products = [
    ['id' => 101, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
    ['id' => 102, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
    ['id' => 103, 'name' => 'T-Shirt', 'category' => 'Apparel', 'price' => 25],
    ['id' => 104, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 30],
    ['id' => 105, 'name' => 'Jeans', 'category' => 'Apparel', 'price' => 60]
];

$groupedProducts = [];

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

print_r($groupedProducts);

// Example: Accessing grouped data
// echo "Electronics products:
";
// foreach ($groupedProducts['Electronics'] as $product) {
//     echo "- " . $product['name'] . " ($[" . $product['price'] . "])
";
// }
?>
How it works: This snippet demonstrates how to group an array of associative arrays by a common key, in this case, 'category'. It iterates through the original array and, for each item, uses the value of the specified key (e.g., 'Electronics' or 'Apparel') as the key in a new array. This effectively creates sub-arrays containing all items that share that common key value, making it easier to process or display data categorized together.

Need help integrating this into your project?

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

Hire DigitalCodeLabs