简体   繁体   中英

PHP Sorting Array Using usort() Not Working

I have this array :

Array
(
    [0] => Array
        (
            [timestamp] => lm81-1527799632244
            [robo] => C4
            [price] => 53.83600000
        )

    [1] => Array
        (
            [timestamp] => lm81-1527799632244
            [robo] => RE
            [price] => 53.83600000
        )

    [2] => Array
        (
            [timestamp] => lm81-1527799632244
            [robo] => C4
            [price] => 0.09188900
        )

    [3] => Array
        (
            [timestamp] => lm81-1527799632244
            [robo] => RE
            [price] => 0.09188900
        )

    [4] => Array
        (
            [timestamp] => lm81-1527799632244
            [robo] => C4
            [price] => 584.80000000
        )

)

and I'm expecting result like this (sort by robo DESC) :

Array
(
    [0] => Array
        (
            [timestamp] => lm81-1527799632244
            [robo] => RE
            [price] => 53.83600000
        )

    [1] => Array
        (
            [timestamp] => lm81-1527799632244
            [robo] => RE
            [price] => 0.09188900
        )

    [2] => Array
        (
            [timestamp] => lm81-1527799632244
            [robo] => C4
            [price] => 53.83600000
        )

    [3] => Array
        (
            [timestamp] => lm81-1527799632244
            [robo] => C4
            [price] => 0.09188900
        )

    [4] => Array
        (
            [timestamp] => lm81-1527799632244
            [robo] => C4
            [price] => 584.80000000
        )

)

and I already done this :

    usort($dc_array_process, function($a, $b) {
        return $a['robo'] - $b['robo'];
    });

but my array still not in DESC order. any idea what did I do wrong?

If you are sorting string values, you should use strcmp

usort($dc_array_process, function($a, $b) {
    return strcmp($a['robo'], $b['robo']);
});

or

usort($dc_array_process, function($a, $b) {
    return -strcmp($a['robo'], $b['robo']);  //negative to reverse
});

document:

int strcmp ( string $str1 , string $str2 )

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Because arithmetic - causes values to be converted to int .

usort($dc_array_process, function($a, $b) {
    return strcmp($a['robo'], $b['robo']);
});

As per the manual , the comparison function passed into usort must…

return an integer less than, equal to, or greater than zero

…for the order to be correctly determined. As the values you're attempting to sort are strings, the minus operation you're using therefore won't work.

Try using strcmp in the return…

return strcmp( $a['robo'], $b['robo'] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM