下面的代码应该将 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);
下面的代码应该将 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);
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
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] =>
)