I have an array with some elements inside, each one of them has a name and an id. For example:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => a
)
[1] => stdClass Object
(
[id] => 2
[name] => b
)
[2] => stdClass Object
(
[id] => 3
[name] => c
)
[3] => stdClass Object
(
[id] => 4
[name] => d
)
[4] => stdClass Object
(
[id] => 5
[name] => e
)
)
And what I want to do with them, is allow some preferred elements to be defined in another array, and then sort this one so that those "preferred" ones will appear first.
For example here, if my user now says that he prefers items with the id's 4, 5, and 6, then the order of these items should result in this:
Array
(
[0] => stdClass Object
(
[id] => 4
[name] => d
)
[1] => stdClass Object
(
[id] => 5
[name] => e
)
[2] => stdClass Object
(
[id] => 1
[name] => a
)
[3] => stdClass Object
(
[id] => 2
[name] => b
)
[4] => stdClass Object
(
[id] => 3
[name] => c
)
)
The 4 and 5 now appear first, because they were preferred, the fact that 6 doesn't actually exist makes no difference (it was just preferred, not mandatory), and the rest of them are then listed afterwards in an irrelevant order.
Now, statically, I know I can achieve this exact behavior by doing this:
usort($elements, function($a, $b) { return in_array($a->id, [4,5,6]) ? -1 : 1; });
This works, and it will sort the elements with the id's 4 and 5 to the top. But if I want those [4,5,6]
to be in a variable, because they come from another source (they aren't static), then I can't make this work... Defining them in an array called $preferred
and then using global $preferred
inside the function call results in the value of $preferred
being NULL
.
Which seems weird, because it seems like a sensible thing to be doing.
So what is my alternative then?