我有一個多維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;
}
和你的嘗試是? –
檢查是否有幫助:http://stackoverflow.com/a/3805256/5645769 –
@TareqMahmood感謝您的參考。但是,針對該帖子列出的解決方案似乎僅適用於多維陣列中的第一級。他們沒有解決我嵌套數組的問題。 – skiindude22