ksort produces wrong result when dealing with alphanumeric characters

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


        
6条回答
  •  太阳男子
    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');
    

提交回复
热议问题