Hello.
I'm trying to sort a collection by a custom order using the keys of the collection once it's grouped.
Take this collection for example:
$staff = collect([
[ "name" => "John", "role" => "Producer" ],
[ "name" => "Phoebe", "role" => "Editor" ],
[ "name" => "Joanne", "role" => "Producer" ],
[ "name" => "Kevin", "role" => "Director" ],
[ "name" => "Christine", "role" => "Director" ],
]);
Firstly, I want to group them by role, which is easy enough using groupBy():
$staff = collect([
[ "name" => "John", "role" => "Producer" ],
[ "name" => "Phoebe", "role" => "Editor" ],
[ "name" => "Joanne", "role" => "Producer" ],
[ "name" => "Kevin", "role" => "Director" ],
[ "name" => "Christine", "role" => "Director" ],
])
->groupBy("role");
which will give me:
array:3 [▼
"Producer" => array:2 [▼
0 => array:2 [▼
"name" => "John"
"role" => "Producer"
]
1 => array:2 [▼
"name" => "Joanne"
"role" => "Producer"
]
]
"Editor" => array:1 [▼
0 => array:2 [▼
"name" => "Phoebe"
"role" => "Editor"
]
]
"Director" => array:2 [▼
0 => array:2 [▼
"name" => "Kevin"
"role" => "Director"
]
1 => array:2 [▼
"name" => "Christine"
"role" => "Director"
]
]
]
but then I want to be able to pass a custom order (most likely using an array) so I can sort the collection using this custom order, for example:
$order = ["Editor", "Director", "Producer"];
so I can achieve:
[
"Editor" => [
// Array of editors
],
"Director" => [
// Array of directors
],
"Producer" => [
// Array of producers
]
]
I can achieve this using a couple of foreach loops, but I'm just wondering how to achieve this using sortBy() or sort(). I've tried using both and passing through a callback but it always returns an error.
Any help is appreciated.
Cheers.