I have an array of rows from MySQL query. What I need to do is sort them by one of the fields (unsigned int type). I looked through reference, but did not understand how exactly do I sort arrays of objects, because PHP does not seem to have something like operator overloading (what you do in C++), and some existing functions say they're unstable, meaning that with 2 equal elements their position in sorted array is undefined, which sounds really weird IMO. So, what's the general approach in PHP when you need to sort an array of objects?
1 Answer
You'll need to write your own function to do the comparison. Once you have that function, you can then use usort - http://php.net/manual/en/function.usort.php
Note that this also works with sorting an array of objects, you just have to change your comparison function.
2 Comments
Barsik the Cat
What's with If two members compare as equal, their relative order in the sorted array is undefined.?? Can I make it so that my comparison function never returns 0 and acts purely like "<" operator?
ivanivan
Of course you can. All the usort() function cares about is that it can pass 2 things to your function and it returns a -1, 1, or 0. Just decide if you want equal values to always return as "less than" or "greater than" and go for it :)