PHP排序数组使用usort()不工作

时间:2018-06-03 14:02:08

标签: php

我有这个数组:

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
        )

)

我期待这样的结果(按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
        )

)

我已经这样做了:

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

但我的数组仍未处于DESC顺序。我知道我做错了什么?

3 个答案:

答案 0 :(得分:2)

如果要对string值进行排序,则应使用strcmp

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

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

文件:

  

int strcmp(string $ str1,string $ str2)

     

返回<如果str1小于str2,则为0; >如果str1大于,则为0   str2,如果它们相等则为0。

答案 1 :(得分:1)

因为算术-导致值转换为 int

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

答案 2 :(得分:0)

根据the manual,传递给usort的比较函数必须......

  

返回小于,等于或大于零的整数

...为了正确确定订单。由于您尝试排序的值是字符串,因此您使用的减号操作无法正常工作。

尝试在返回中使用strcmp ......

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