I have a $result variable in PHP from a MySQL query & I would like to sort it (with PHP) on 2 different columns.
I am doing this anytime a user clicks a different sort method, so I don’t want to have to redo the MySQL query with ORDER BY …., …. each time.
It would probably be more efficient to have MySQL do the ordering for you, but if you want to do it in PHP, check out usort which will let you sort an array using a callback function to decide the ordering.
If your $result is an array of associative database rows, here’s a very simple example of using usort to sort on a string column ‘foo’ …
Here’s how you’d do a numeric sort…
That illustrates the basics of how to use usort, but how might we sort on several columns at once? Here’s how we could combine our comparison callbacks to illustrate this by sorting on ‘foo’ and then ‘bar’…
You could unroll
sortFooBarinto a single function, but this illustrates the technique: compare first column, if same, compare second column, and so on.