php associative array key order (not sort)

前端 未结 5 813
余生分开走
余生分开走 2020-12-17 10:38

My array:

$data = array(\'two\' => 2, \'one\' => 1, \'three\' => 3);

Now, with when I iterate the array, the first value that wil

5条回答
  •  孤城傲影
    2020-12-17 11:14

    See ksort and uksort.

    Here's a working example:

     2, 'one' => 1, 'three' => 3);
    print_r($data);
    ksort($data);
    echo "ksort:\n";
    print_r($data);
    uksort($data,'cmp');
    echo "uksort:\n";
    print_r($data);
    function cmp($a, $b)
    {
        $num=' one two three four five six seven eight nine ten';
        $ai = stripos($num,$a);
        $bi = stripos($num,$b);
        if ($ai>0 && $bi>0) {
            return ($ai > $bi) ? 1 : -1;
        }
        return strcasecmp($a, $b);
    }
    

    Output:

    Array
    (
        [two] => 2
        [one] => 1
        [three] => 3
    )
    ksort:
    Array
    (
        [one] => 1
        [three] => 3
        [two] => 2
    )
    uksort:
    Array
    (
        [one] => 1
        [two] => 2
        [three] => 3
    )
    

    Run this: http://codepad.org/yAK1b1IP

提交回复
热议问题