I found a few questions about this, but I feel I have a pretty special case here so I'm asking a new one.
I need to sort an array of users first by their (array) of titles and then by last name, consider the following code:
<?php
$users = [
[
'lastName' => 'Clarks',
'titles' => ['Manager', 'Supervisor']
],
[
'lastName' => 'Clarkson',
'titles' => ['Sales']
],
[
'lastName' => 'Adams',
'titles' => ['Supervisor']
],
[
'lastName' => 'Adams',
'titles' => ['Manager', 'Senior Manager']
],
[
'lastName' => 'Clarkson',
'titles' => ['Manager']
],
[
'lastName' => 'Davids',
'titles' => ['Senior Manager']
]
];
And the order I want is:
<?php
$order = [
'Senior Manager',
'Manager',
'Supervisor'
];
If there are several managers they should be sorted by lastName, so the output in this case would be:
<?php
$sorted = [
[
'lastName' => 'Adams',
'titles' => ['Manager', 'Senior Manager']
],
[
'lastName' => 'Davids',
'titles' => ['Senior Manager']
],
[
'lastName' => 'Clarks',
'titles' => ['Manager', 'Supervisor']
],
[
'lastName' => 'Clarkson',
'titles' => ['Manager']
],
[
'lastName' => 'Adams',
'titles' => ['Supervisor']
],
[
'lastName' => 'Clarkson',
'titles' => ['Sales']
]
];
I've tried something along these lines but can't get it to work and find it a little hard to debug usort:
<?php
foreach ($order as $title) {
usort($users, function ($a, $b) use ($title) {
# Both have the title
if (in_array($title, $a['titles']) and in_array($title, $b['titles']) ) {
# Sort by name
return strcmp($a['lastName'], $b['lastName']);
}
# A has the title
elseif (in_array($title, $a['titles'])) {
return 1;
}
# B has the title
elseif (in_array($title, $b['titles'])) {
return -1;
}
# No-one has the title
return strcmp($a['lastName'], $b['lastName']);
});
}
$ordervalues, I assume you mean 'Senior Manager' and then 'Manager' etc., what if there are ones with 'Senior Manager' and 'Manager' and another with 'Senior Manager' and 'Supervisor'?