2015-12-29 37 views
5

我有一個多維PHP數組,我正在使用它來生成一個分層的UL樹。但是,在顯示UL樹之前,我想按照'name'屬性按字母順序對數組中的每個級別進行排序。我想象一個遞歸檢查每個級別的函數,按字母順序對其進行組織,然後進入下一個級別對該級別進行排序。但我不知道該怎麼做。任何幫助,將不勝感激!排序嵌套的多維PHP數組的每個級別

我的數組:

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 
       ) 
      ) 
     ) 
    ) 
    ) 

我的嘗試,這是中移動的順序,但它仍然是不按字母順序排列。請注意,在陣列($此, '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; 
} 

UPDATE:解決方案

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; 
    } 
+3

和你的嘗試是? –

+0

檢查是否有幫助:http://stackoverflow.com/a/3805256/5645769 –

+0

@TareqMahmood感謝您的參考。但是,針對該帖子列出的解決方案似乎僅適用於多維陣列中的第一級。他們沒有解決我嵌套數組的問題。 – skiindude22

回答

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 
+0

明智地使用經驗... –

+0

@BasheerAhmed你甚至認爲這是什麼意思?你是一個令人困惑的人。 –

+0

哦,我的天啊,甚至我沒有意識到.. :) –