0

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?

Saint Robson
  • 5,475
  • 18
  • 71
  • 118

3 Answers3

2

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.

shawn
  • 4,305
  • 1
  • 17
  • 25
1

Because arithmetic - causes values to be converted to int.

usort($dc_array_process, function($a, $b) {
    return strcmp($a['robo'], $b['robo']);
});
u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

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'] );
John Parker
  • 54,048
  • 11
  • 129
  • 129