PHP

Group Associative Arrays by a Common Key Value

Discover how to transform a flat list of associative arrays into a grouped structure based on the value of a specified key. Perfect for organizing data for display.

function groupArrayByKey(array $array, string $key): array
{
    $grouped = [];
    foreach ($array as $item) {
        if (isset($item[$key])) {
            $grouped[$item[$key]][] = $item;
        } else {
            // Handle items without the grouping key, e.g., group them under a 'null' or 'misc' key
            $grouped['__misc__'][] = $item;
        }
    }
    return $grouped;
}

$products = [
    ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics'],
    ['id' => 2, 'name' => 'Keyboard', 'category' => 'Electronics'],
    ['id' => 3, 'name' => 'Shirt', 'category' => 'Apparel'],
    ['id' => 4, 'name' => 'Mouse', 'category' => 'Electronics'],
    ['id' => 5, 'name' => 'Pants', 'category' => 'Apparel'],
];

$groupedProducts = groupArrayByKey($products, 'category');
print_r($groupedProducts);
How it works: The `groupArrayByKey` function iterates through an array of associative arrays and reorganizes them into a new array where the keys are the distinct values of the specified `$key`. Each value of the new array is itself an array containing all the original items that share that common key value. This pattern is invaluable for presenting data categorized by attributes like category, status, or user ID.

Need help integrating this into your project?

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

Hire DigitalCodeLabs