ski*_*e22 5 php arrays sorting multidimensional-array
我有一个多维PHP数组,我用它来生成分层UL树.但是,在显示UL树之前,我想通过'name'属性按字母顺序对数组中的每个级别进行排序.我想象一个递归检查每个级别的函数,按字母顺序组织它,然后移动到下一级别来排序该级别.但我不知道该怎么做.任何帮助,将不胜感激!
我的阵列:
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
)
)
)
)
)
Run Code Online (Sandbox Code Playgroud)
我的尝试,即移动订单,但它仍然不是按字母顺序排列的.注意,CodeIgniter需要数组($ 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;
}
Run Code Online (Sandbox Code Playgroud)
更新:解决方案
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;
}
Run Code Online (Sandbox Code Playgroud)
我输入了一种算法思维方式,以便您可以自己实现代码。此外,我不想夺走你所有的乐趣!:-)
如果这对您来说还不够,请查看此。
function example(element) {
if (no children exist) return
if (only one element exist on this level)
// if this code is reached, this element has children
example(children element)
return
names = { array of all name attributes of all elements on this level }
sort(names)
[0] => names[0]
[1] => names[1]
.. and so on for however many elements there are
return
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
132 次 |
| 最近记录: |