对嵌套的多维PHP数组的每个级别进行排序

时间:2015-12-29 05:37:16

标签: php arrays sorting multidimensional-array

我有一个多维PHP数组,用于生成分层UL树。但是,在显示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需要数组($ 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;
    }

1 个答案:

答案 0 :(得分:2)

我输入了一种算法思维方式,因此您可以自己实现代码。此外,我不想带走你所有的乐趣! : - )

如果还不够,请查看this

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