<?php

    $a = array(
        'a'=>'7833',
        'd'=>'1297',
        'c'=>'341',
        '1'=>'67',
        'b'=>'225',
        '3'=>'24',
        '2'=>'44',
        '4'=>'22',
        '0'=>'84'
    );

    ksort($a);

    print_r($a);

The above code produces the following output.

Array
(
    [0] => 84
    [a] => 7833
    [b] => 225
    [c] => 341
    [d] => 1297
    [1] => 67
    [2] => 44
    [3] => 24
    [4] => 22
)

Why does ksort give wrong result?

有帮助吗?

解决方案

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

其他提示

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');

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

This will work:

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

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

Cheers!

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

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
)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top