13

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

2 Answers 2

31

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

function mysort($a, $b) {
   return strnatcmp($a->rate, $b->rate);
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.