How to perform a natural sort in php using usort
Asked Answered
S

2

12

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
Slickenside answered 14/9, 2012 at 14:45 Comment(0)
N
29

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

function mysort($a, $b) {
   return strnatcmp($a->rate, $b->rate);
}
Naashom answered 14/9, 2012 at 14:47 Comment(1)
Just a small note. The answer above will return 1, 2, 3 etc, But the question asked for 4, 3, 2, 1. All you need to do is reverse the call e.g $b->rate,$a->rate.Slickenside
R
0

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.

Regularly answered 24/12, 2019 at 3:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.