Skip to content
Advertisement

PHP Group Array By result of function on value

I have an array that’s basically a simple collection of objects.

So

[obj1,obj2,obj3]

All instances of the same class. I then want to perform a map or filter to group these by a value in those objects.

$userIds = array_map(function($obj){
    return = $obj->getUserId();
}, $objs);

And what I want is a result like this, where all the objects are sorted by their user ids:

[
'user1' => [$obj1],
'user2' => [$obj2, $obj4, $obj6],
'user3' => [$obj3, $obj5],
]

Looking for a way to do this cleanly with array functions to avoid a messy foreach and overwriting a variable. I have a few ideas but knowing PHP there’s probably a standard function that does it.

Advertisement

Answer

array_map() won’t allow you to declare the keys as you iterate.

array_reduce() is an appropriate function for this task; it is also indicative of the fact that the first level in the output array will likely have a smaller count than the original array.

$objsByUserId = array_reduce(
    $objs,
    function($result, $obj) {
        $result[$obj->getUserId()][] = $obj;
        return $result;
    },
    []
);

This will iterate all rows in $objs and push each encountered object as a new element in a group based on the returned userId.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement