ksort produces wrong result when dealing with alphanumeric characters

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


        
6条回答
  •  粉色の甜心
    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

提交回复
热议问题