John Davidson

PHP Group Array By result of function on value

0 comments
Message:


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.



My Answer:
>getUserId();_}, $objects);_// $userIds is now an array of user IDs_// Group objects by user ID_$groupedObjects = [];_foreach($objects as $obj){_ $userId = $obj->getUserId();_ if(!isset($groupedObjects[$userId])){_ $groupedObjects[$userId] = [];_ }_ $groupedObjects[$userId][] = $obj;_}

Rate this post

5 of 5 based on 5372 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us