问题
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
回答1:
Use strnatcmp for your comparison function. e.g. it's as simple as
function mysort($a, $b) {
return strnatcmp($a->rate, $b->rate);
}
回答2:
There are a few ways to sort by your Rate
properties in a numeric and descending.
Here are some demonstrations based on your input:
$objects = [
(object)['Rate' => '10'],
(object)['Rate' => '1'],
(object)['Rate' => '2'],
(object)['Rate' => '20'],
(object)['Rate' => '22']
];
array_multisort() is clear and expressive: (Demo)
array_multisort(array_column($objects, 'Rate'), SORT_DESC, SORT_NUMERIC, $objects);
usort(): (Demo)
usort($objects, function($a, $b) {
return $b->Rate <=> $a->Rate;
});
usort() with arrow function syntax from PHP7.4: (Demo)
usort($objects, fn($a, $b) => $b->Rate <=> $a->Rate);
PHP's spaceship operator (<=>
) will automatically evaluate two numeric strings as numbers -- no extra/iterated function calls or flags are necessary.
来源:https://stackoverflow.com/questions/12426825/how-to-perform-a-natural-sort-in-php-using-usort