How to perform a natural sort in php using usort

后端 未结 2 544
情歌与酒
情歌与酒 2020-12-10 05:40

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

相关标签:
2条回答
  • 2020-12-10 06:00

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

    function mysort($a, $b) {
       return strnatcmp($a->rate, $b->rate);
    }
    
    0 讨论(0)
  • 2020-12-10 06:14

    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.

    0 讨论(0)
提交回复
热议问题