PHP

Grouping PHP Array Elements by a Specific Property

Efficiently organize and group an array of associative arrays based on a shared key or property, simplifying data categorization in PHP.

<?php

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

$users = [
    ['id' => 1, 'name' => 'Alice', 'role' => 'admin'],
    ['id' => 2, 'name' => 'Bob', 'role' => 'editor'],
    ['id' => 3, 'name' => 'Charlie', 'role' => 'admin'],
    ['id' => 4, 'name' => 'David', 'role' => 'viewer']
];

$usersByRole = groupByKey($users, 'role');
/*
$usersByRole will be:
[
    'admin' => [
        ['id' => 1, 'name' => 'Alice', 'role' => 'admin'],
        ['id' => 3, 'name' => 'Charlie', 'role' => 'admin']
    ],
    'editor' => [
        ['id' => 2, 'name' => 'Bob', 'role' => 'editor']
    ],
    'viewer' => [
        ['id' => 4, 'name' => 'David', 'role' => 'viewer']
    ]
]
*/

?>
How it works: This function iterates through an array of associative arrays. For each inner array, it extracts the value associated with the specified `$key`. This value is then used as a new key in the `$grouped` array, and the current inner array is appended to the list corresponding to its group key. This is perfect for organizing data by categories or attributes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs