简体   繁体   中英

Cant sort array according to key using usort

I have and array looks like this

Array
(
    [0] => Array
        (
            [key] => 0
            [val] => 0
        )

    [1] => Array
        (
            [key] => 11
            [val] => 1:1
        )

    [2] => Array
        (
            [key] => 1100
            [val] => 1:100
        )

    [3] => Array
        (
            [key] => 112
            [val] => 1:12
        )

    [4] => Array
        (
            [key] => 1144
            [val] => 1:144
        )

    [5] => Array
        (
            [key] => 1146
            [val] => 1:146
        )

    [6] => Array
        (
            [key] => 116
            [val] => 1:16
        )

    [7] => Array
        (
            [key] => 118
            [val] => 1:18
        )

    [8] => Array
        (
            [key] => 120
            [val] => 1:20

I want to sort it by the KEY key in the array

I use the following code

     usort($arrScale,"cmd");

function cmp($a, $b)
{
    if ($a["key"] == $b["key"]) {
        return 0;
    }
    return ($a["key"] < $b["key"]) ? -1 : 1;
}

1100 and 1144 should be more towards the end?? Am I doing something wrong?

The key values are strings, and by string comparison rules "1144" is 'less' than "116". Cast them to int for your comparisons.

function cmp($a, $b) 
{ 
    $aKey = (int) $a["key"];
    $bKey = (int) $b["key"];

    if ($aKey == $bKey) { 
        return 0; 
    } 
    return ($aKey < $bKey) ? -1 : 1; 
} 

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