Created
January 25, 2017 19:58
-
-
Save robertvrabel/786e84b9703e9a948a1a2b0b16893b3f to your computer and use it in GitHub Desktop.
Sort profile users by group
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Profile users are in multiple groups. | |
* | |
* The expected $sortedArray should be grouped by group_id (which is the key) to array of users who are in that group. | |
* | |
* The only groups that should be in $sortedArray should be ones that exist in $statuses. | |
*/ | |
$statuses = [ | |
2330 => "Chair", | |
2292 => "Full-time", | |
2293 => "Lecturer", | |
2294 => "Tenured", | |
2295 => "Tenured Track", | |
2296 => "Part-time", | |
2297 => "Administration", | |
2311 => "Advisor", | |
2312 => "Emeritus", | |
2313 => "Ph.D. Student", | |
2314 => "Staff", | |
]; | |
$profiles = [ | |
1000 => [ | |
'user_id' => 1000, | |
'groups' => [ | |
2335 => "Social-Personality", | |
2367 => "Foundations of Ethics and Law", | |
2292 => "Full-time", | |
2293 => "Lecturer", | |
], | |
'data' => [ | |
'first_name' => 'Han', | |
'last_name' => 'Solo', | |
], | |
], | |
1001 => [ | |
'user_id' => 1001, | |
'groups' => [ | |
2415 => "Psychology", | |
2367 => "Foundations of Ethics and Law", | |
2312 => "Emeritus", | |
2293 => "Lecturer", | |
], | |
'data' => [ | |
'first_name' => 'Luke', | |
'last_name' => 'Skywalker', | |
], | |
], | |
]; | |
// Expected sorted array. group_id to array of user_ids, where group_id exists as a key in $statuses | |
$sortedArray = [ | |
2292 => [1000], | |
2293 => [1000, 1001], | |
2312 => [1001], | |
]; | |
/** ------- Example Solution ------- **/ | |
$profiles = collect($profiles); | |
$sortedArray = collect($statuses) | |
->map(function ($status, $group_id) use ($profiles) { | |
// Get the users that have this status | |
$groups = $profiles->filter(function ($profile, $user_id) use ($status, $group_id) { | |
return array_key_exists($group_id, $profile['groups']); | |
}); | |
return $groups->keys(); | |
}) | |
->filter(function($group) { | |
return ! $group->isEmpty(); | |
}) | |
->toArray(); | |
dd($sortedArray); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tried to tackle it from another angle but it's definitely no better: