I have a usort function with a single line: return 0.
I tried to use it on an Array of stdClass objects, and it changes
their order, how is that possible?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
It's because that function means "I really don't care how they are sorted, they are equal to me". With this simple sample I receive reversed array:
So it looks like PHP loops the array in reverse order in function
usort
. So, note theusort
manual states thatThe property you assume is called stability: A stable sorting algorithm will not change the order of elements that are equal.
php's sorting functions are not stable (because non-stable sorts may be slightly faster). From the documentation of
usort
:If you want a stable sorting algorithm, you must implement it yourself.
If you're looking for a quick solution for a stable
usort
, you could useuksort
like in the following example:This works as expected only if the initial indices (keys) of
$array
are in ascending order.