← Back to all snippets
PHP

Grouping Multidimensional PHP Arrays by Key

Efficiently organize and group records within a PHP array of associative arrays based on the value of a specified key, which is highly useful for data structuring.

<?php
$articles = [
    ['id' => 1, 'title' => 'PHP Basics', 'category' => 'Programming'],
    ['id' => 2, 'title' => 'Web Security Tips', 'category' => 'Security'],
    ['id' => 3, 'title' => 'Advanced PHP Features', 'category' => 'Programming'],
    ['id' => 4, 'title' => 'Database Best Practices', 'category' => 'Databases'],
    ['id' => 5, 'title' => 'SQL Injection Guide', 'category' => 'Security'],
];

function groupByKey(array $array, string $key): array
{
    $grouped = [];
    foreach ($array as $item) {
        if (isset($item[$key])) {
            $grouped[$item[$key]][] = $item;
        }
    }
    return $grouped;
}

$groupedArticles = groupByKey($articles, 'category');

echo json_encode($groupedArticles, JSON_PRETTY_PRINT);
/*
Expected output:
{
    "Programming": [
        {
            "id": 1,
            "title": "PHP Basics",
            "category": "Programming"
        },
        {
            "id": 3,
            "title": "Advanced PHP Features",
            "category": "Programming"
        }
    ],
    "Security": [
        {
            "id": 2,
            "title": "Web Security Tips",
            "category": "Security"
        },
        {
            "id": 5,
            "title": "SQL Injection Guide",
            "category": "Security"
        }
    ],
    "Databases": [
        {
            "id": 4,
            "title": "Database Best Practices",
            "category": "Databases"
        }
    ]
}
*/
?>
How it works: This snippet demonstrates how to group a multidimensional array (an array of associative arrays) based on the value of a specified key. The `groupByKey` function iterates through each item, uses the value of the given key as the new array key, and appends the item to the corresponding group. This pattern is invaluable for organizing data for reports or displays.

Need help integrating this into your project?

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

Hire DigitalCodeLabs