PHP

Grouping an Array of Associative Arrays by a Key

Learn how to efficiently group a flat array of associative arrays into a nested structure based on a common key using PHP for better data organization.

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 key, e.g., add to a 'misc' group or skip
            $grouped['__misc__'][] = $item;
        }
    }
    return $grouped;
}

$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', 'price' => 300], // Item without category
];

$groupedByCategory = groupArrayByKey($products, 'category');
/*
// Example output for 'Electronics':
$groupedByCategory['Electronics'] = [
    ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
    ['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25],
    ['id' => 3, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
];
$groupedByCategory['__misc__'] = [['id' => 6, 'name' => 'Monitor', 'price' => 300]];
*/
How it works: This function iterates through an array of associative arrays. For each inner array, it uses the value of the specified `$key` to create a new key in the `$grouped` array. All inner arrays sharing the same value for `$key` are collected into a nested array under that key. It also includes basic handling for items missing the specified key, adding them to a '__misc__' group.

Need help integrating this into your project?

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

Hire DigitalCodeLabs