ksort produces wrong result when dealing with alphanumeric characters

后端 未结 6 788
感动是毒
感动是毒 2021-01-18 18:40
\'7833\',
        \'d\'=>\'1297\',
        \'c\'=>\'341\',
        \'1\'=>\'67\',
        \'b\'=>\'225\',
            


        
相关标签:
6条回答
  • 2021-01-18 18:54

    See this page for an overview of the different sort functions in php: http://php.net/manual/en/array.sorting.php

    If you want it sorted by key, then use asort(), which produces this output:

    Array
    (
        [4] => 22
        [3] => 24
        [2] => 44
        [1] => 67
        [0] => 84
        [b] => 225
        [c] => 341
        [d] => 1297
        [a] => 7833
    )
    
    0 讨论(0)
  • 2021-01-18 18:59

    ksort(array, sortingtype) sorts an associative array in ascending order, according to the keys, for a specified sorting type (sortingtype). But because sortingtype has a default value of SORT_REGULAR, when the keys have a combination of numbers and strings, that weid or unexpected behaviour occurs.

    You must always remember to explicitly specify the sorting type, to avoid it confusing numbers with strings.

    $a = array('a'=>'7833','d'=>'1297','c'=>'341','1'=>'67','b'=>'225','3'=>'24','2'=>'44','4'=>'22','0'=>'84');
    ksort($a, SORT_STRING);
    foreach ($a as $key => $val) {
        echo "$key = $val\n";
    }
    

    PHP documentation on ksort

    0 讨论(0)
  • 2021-01-18 19:16

    Try ksort($a, SORT_STRING) to force string comparisons on the keys.

    0 讨论(0)
  • 2021-01-18 19:17

    This will work:

    <?php ksort($a,SORT_STRING); ?>
    

    Checkout the other sort_flags here http://www.php.net/manual/es/function.sort.php

    Cheers!

    0 讨论(0)
  • 2021-01-18 19:19

    You'll want to use the SORT_STRING flag. SORT_REGULAR would compare items with their current types, in which case the number 1 does come after the string 'a':

    php -r "echo 1 > 'a' ? 'yes' : 'no';" // yes
    
    0 讨论(0)
  • 2021-01-18 19:19

    The default sorting uses SORT_REGULAR.

    This takes the values and compares them as described on the comparison operators manual page. For the times when the string keys, in your example, are compared with zero; those strings are converted to numbers (all 0) for comparision. If two members compare as equal, their relative order in the sorted array is undefined. (Quoted from usort() manual page.)

    If you want the sorted output to have numbers before letters, you should use SORT_NATURAL as of PHP 5.4. SORT_STRING will also do the job only if the numbers remain single digits.

    SORT_NATURAL (PHP 5.4 or above) gives keys ordered as:

    0,1,2,4,11,a,b,c
    

    SORT_STRING gives keys ordered as:

    0,1,11,2,4,a,b,c
    

    An alternative to SORT_NATURAL for PHP less than 5.4, would be use uksort().

    uksort($a, 'strnatcmp');
    
    0 讨论(0)
提交回复
热议问题