Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a natural sort in php using usort

Tags:

php

sorting

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
like image 898
TheAlbear Avatar asked Sep 14 '12 14:09

TheAlbear


People also ask

How does Usort work in PHP?

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.

What is natural order sorting in PHP?

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.

Is PHP Usort stable?

Sorting functions in PHP are currently unstable, which means that the order of “equal” elements is not guaranteed.

Which function should we use to sort the array in natural order in PHP?

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.


1 Answers

Use strnatcmp for your comparison function. e.g. it's as simple as

function mysort($a, $b) {
   return strnatcmp($a->rate, $b->rate);
}
like image 195
Marc B Avatar answered Nov 12 '22 10:11

Marc B