Skip to content
Advertisement

How to combine multiple sorting functions

It works like a charm in SQL:

JavaScript

But what if we have such data in PHP array. How can we do the same? For example, if I have

JavaScript

and I want to sort it by age in descending order and then by name in ascending order. Just like in the SQL above. So the right sequence of names is: Lue, Alfred, Mark, Ameli, Barb. See db-fiddle.

The wrong attempt to get it in PHP is:

JavaScript

Each of two usort calls works fine, but it overrides the previous result, while I want to combine them all together. Ideally, I’d like to have a function that accepts any amount of Callable to usort them all.

Please advise.

Update: As reasonable commented bellow, array_multisort is suitable for sorting regular array like this. But I’d like to find solution to combine comparator closures. ANY comparators, even like this one.
By the way, SQL allows to sort by expression, not only by simple field.

Advertisement

Answer

Here’s a way to do it:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement