PHP

Grouping Associative Arrays by a Common Key in PHP

Discover how to efficiently group elements within an array of associative arrays (or objects) into nested arrays, categorizing them by a shared key's value.

<?php

/**
 * Groups an array of associative arrays by a specified key.
 *
 * @param array $data The array of associative arrays to group.
 * @param string $key The key by which to group the arrays.
 * @return array The grouped array.
 */
function groupArrayByKey(array $data, string $key): array
{
    $grouped = [];
    foreach ($data as $item) {
        if (isset($item[$key])) {
            $grouped[$item[$key]][] = $item;
        } else {
            // Handle items without the specified key, e.g., place in a 'null' group
            $grouped['[ungrouped]'][] = $item; 
        }
    }
    return $grouped;
}

// Example Usage:
$products = [
    ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
    ['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25],
    ['id' => 3, 'name' => 'Book', 'category' => 'Books', 'price' => 15],
    ['id' => 4, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
    ['id' => 5, 'name' => 'Magazine', 'category' => 'Books', 'price' => 10],
    ['id' => 6, 'name' => 'Headphones', 'category' => 'Audio', 'price' => 150],
    ['id' => 7, 'name' => 'Tablet', 'category' => 'Electronics', 'price' => 500],
];

echo "Original Products:
";
foreach ($products as $product) {
    echo json_encode($product) . "
";
}

$groupedByCategory = groupArrayByKey($products, 'category');

echo "
Grouped by Category:
";
foreach ($groupedByCategory as $category => $items) {
    echo "--- " . $category . " ---
";
    foreach ($items as $item) {
        echo "- " . $item['name'] . "
";
    }
}
?>
How it works: This function takes an array of associative arrays and a key, then reorganizes them into a new associative array where keys are the unique values of the specified grouping key, and each value is an array containing all original items that share that key value. This pattern is incredibly useful for categorizing data for display or further processing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs