I’ll add the entire post below, but please also read it on stackoverflow the answer deserves the attention.
Thank you Jon for some great code and explanation.
Introducing: a very generalized solution for PHP 5.3+
I ‘d like to add my own solution here, since it offers features that other answers do not.
Specifically, advantages of this solution include:
- It’s reusable: you specify the sort column as a variable instead of hardcoding it.
- It’s flexible: you can specify multiple sort columns (as many as you want) — additional columns are used as tiebreakers between items that initially compare equal.
- It’s reversible: you can specify that the sort should be reversed — individually for each column.
- It’s extensible: if the data set contains columns that cannot be compared in a “dumb” manner (e.g. date strings) you can also specify how to convert these items to a value that can be directly compared (e.g. a
- It’s associative if you want: this code takes care of sorting items, but you select the actual sort function (
- Finally, it does not use
array_multisortis convenient, it depends on creating a projection of all your input data before sorting. This consumes time and memory and may be simply prohibitive if your data set is large.