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 v
Use strnatcmp for your comparison function. e.g. it's as simple as
function mysort($a, $b) {
return strnatcmp($a->rate, $b->rate);
}
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.