2

下面的代码应该将 Banana 放在 apple 之后,但它会放到最后。

$json='{"apple":null,"orange":["s","s2"],"pear":null}';

$json=json_decode($json,true);

$json['Banana']=NULL;

ksort ($json, SORT_NATURAL | SORT_FLAG_CASE);

print_r($json);
4

2 回答 2

0

SORT_NATURAL并且SORT_FLAG_CASE仅适用于 php 版本 > 5.4.0

从这里: http ://www.php.net/manual/en/function.sort.php

在变更日志中

5.4.0   Added support for SORT_NATURAL and SORT_FLAG_CASE as sort_flags
于 2013-05-04T18:16:03.353 回答
0
function natksort(&$array) {
    $keys = array_keys($array);
    natcasesort($keys);

    foreach ($keys as $k) {
        $new_array[$k] = $array[$k];
    }

    $array = $new_array;
    return true;
}

$json='{"apple":null,"orange":["s","s2"],"pear":null}';
$json=json_decode($json,true);
$json['Banana']=NULL;

natksort($json);

print_r($json);

结果:

Array
(
    [apple] => 
    [Banana] => 
    [orange] => Array
        (
            [0] => s
            [1] => s2
        )

    [pear] => 
)
于 2013-05-04T18:33:16.830 回答