php 7 - 按键对多级关联数组进行排序,使其在每个级别上按字典顺序排序
php 7 - sort multilevel associative array by keys to have it sorted on each level lexicographically
在PHP7中,如何对数组的所有级别进行递归排序以使任何相邻键按字典顺序排列?
这个示例数组:
$a = ['c'=>['d'=>1, 'a'=>2], 'b'=>['b'=>3, 'a'=>4], 'a'=>['z','x','y']];
我希望翻译成:
$a = ['a'=>['z','x','y'], 'b'=>['a'=>4, 'b'=>3], 'c'=>['a'=>2, 'd'=>1]];
终于解决了
$a = ['c'=>['d'=>1, 'a'=>2], 'b'=>['b'=>3, 'a'=>4], 'a'=>['z','x','y']];
function array_sort_recursive($arr) {
foreach ($arr as $key => $val) {
if (is_array($val))
$arr[$key] = array_sort_recursive($val);
}
uksort($arr, "strcmp");
return $arr;
}
$b = array_sort_recursive($a);
print_r($b);
试一试:here
在PHP7中,如何对数组的所有级别进行递归排序以使任何相邻键按字典顺序排列?
这个示例数组:
$a = ['c'=>['d'=>1, 'a'=>2], 'b'=>['b'=>3, 'a'=>4], 'a'=>['z','x','y']];
我希望翻译成:
$a = ['a'=>['z','x','y'], 'b'=>['a'=>4, 'b'=>3], 'c'=>['a'=>2, 'd'=>1]];
终于解决了
$a = ['c'=>['d'=>1, 'a'=>2], 'b'=>['b'=>3, 'a'=>4], 'a'=>['z','x','y']];
function array_sort_recursive($arr) {
foreach ($arr as $key => $val) {
if (is_array($val))
$arr[$key] = array_sort_recursive($val);
}
uksort($arr, "strcmp");
return $arr;
}
$b = array_sort_recursive($a);
print_r($b);
试一试:here