Does anyone know what the function is to perform a natural order sort using the usort function in PHP on an object.
Lets say the object ($obj->Rate)has a range of values in
$obj->10
$obj->1
$obj->2
$obj->20
$obj->22
What is I am trying to get the sort function to return
$obj->22
$obj->20
$obj->10
$obj->2
$obj->1
As my current standard sort function
function MySort($a, $b)
{
if ($a->Rate == $b->Rate)
{
return 0;
}
return ($a->Rate < $b->Rate) ? -1 : 1;
}
is returning
$obj->1
$obj->10
$obj->2
$obj->20
$obj->22
The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to the elements present in the array and the old keys are lost.
The natsort() function is used to sorts an array using a "natural order" algorithm. The function implements a sort algorithm but maintains original keys/values. This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations.
Sorting functions in PHP are currently unstable, which means that the order of “equal” elements is not guaranteed.
PHP | natsort() Function. The natsort() function is an inbuilt function in PHP which is used to sort an array by using a “natural order” algorithm.
Use strnatcmp for your comparison function. e.g. it's as simple as
function mysort($a, $b) {
return strnatcmp($a->rate, $b->rate);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With