0

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?

2

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.