【发布时间】:2016-04-02 23:37:19
【问题描述】:
我有一个用于生成分层 UL 树的多维 PHP 数组。但是,在显示 UL 树之前,我想按“名称”属性的字母顺序对数组中的每个级别进行排序。我正在想象一个函数,它递归地检查每个级别,按字母顺序组织它,然后进入下一个级别以对该级别进行排序。但我不知道该怎么做。任何帮助将不胜感激!
我的数组:
Array (
[0] => Array (
[id] => 39348
[parent] => 0
[name] => Test
[children] => Array (
[0] => Array (
[id] => 41911
[parent] => 39348
[name] => Test2
[children] => Array (
[0] => Array (
[id] => 40929
[parent] => 41911
[name] => Test3
[children] => Array (
[0] => Array (
[id] => 40779
[parent] => 40929
[name] => C
)
[1] => Array (
[id] => 40780
[parent] => 40929
[name] => A
)
)
)
)
)
我的尝试是移动顺序,但仍然不是字母顺序。请注意,我正在使用的 CodeIgniter 需要 array($this,'sortByName'):
function recursive_sort($array) {
usort($array, array($this,'sortByName'));
foreach($array as $key => $value) {
if(isset($value['children']) && !empty($value['children']) && is_array($value['children'])) {
$array[$key]['children'] = $this->recursive_sort($value['children']);
}
}
return $array;
}
function sortByName($a, $b){
return $a->name - $b->name;
}
更新:解决方案
function recursive_sort($array,$child='children') {
usort($array,function($a,$b){
return strcasecmp($a['name'], $b['name']);
});
foreach($array as $key => $value) {
if(isset($value[$child]) && !empty($value[$child]) && is_array($value[$child])) {
$array[$key][$child] = $this->recursive_sort($value[$child],$child);
}
}
return $array;
}
【问题讨论】:
-
你的尝试是?
-
如果有帮助,请检查:stackoverflow.com/a/3805256/5645769
-
@TareqMahmood 感谢您的参考。但是,为该帖子列出的解决方案似乎仅适用于多维数组中的第一级。它们没有解决我嵌套数组的情况。
-
您的原始数组和预期输出?
标签: php arrays sorting multidimensional-array