Skip to content

Instantly share code, notes, and snippets.

@robertvrabel
Created January 25, 2017 19:58
Show Gist options
  • Save robertvrabel/786e84b9703e9a948a1a2b0b16893b3f to your computer and use it in GitHub Desktop.
Save robertvrabel/786e84b9703e9a948a1a2b0b16893b3f to your computer and use it in GitHub Desktop.
Sort profile users by group
<?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);
@adamwathan
Copy link

Tried to tackle it from another angle but it's definitely no better:

    $result = collect($profiles)->flatMap(function ($profile) use ($statuses) {
        return collect($profile['groups'])->filter(function ($group, $group_id) use ($statuses) {
            return collect($statuses)->keys()->contains($group_id);
        })->map(function ($group, $group_id) use ($profile) {
            return [
                'user_id' => $profile['user_id'],
                'group_id' => $group_id,
            ];
        });
    })->groupBy('group_id')->map(function ($users) {
        return $users->pluck('user_id');
    })->toArray();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment