PHP

Group PHP Array Elements by a Key

Master grouping a list of associative arrays or objects in PHP by a common property, transforming flat lists into structured, categorized data for easier processing.

<?php
$products = [
    ['id' => 1, 'category' => 'Electronics', 'name' => 'Laptop'],
    ['id' => 2, 'category' => 'Books', 'name' => 'PHP Cookbook'],
    ['id' => 3, 'category' => 'Electronics', 'name' => 'Mouse'],
    ['id' => 4, 'category' => 'Books', 'name' => 'Laravel Guide'],
];

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

print_r($groupedProducts);
?>
How it works: This code snippet shows how to group elements within a flat array based on a specific key's value. It iterates through the original array and dynamically creates new keys in a `$groupedProducts` array. Each new key represents a unique category, and its corresponding value is an array containing all items belonging to that category.

Need help integrating this into your project?

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

Hire DigitalCodeLabs