**算法不必定是獨創,但必定是原創哈!php
我本身給這個算法取個名字,叫「一致無限分類法」。。哈哈!**前端
奉上代碼:(使用的thinkphp框架)算法
public function menu(){ $data = M('menu') -> select(); //獲取數據 $data = $this -> index_to_key($data,'menu_id'); //把primary key轉移到數組索引上去 foreach($data as &$one){ $one['children'] = $this -> search_children($one['menu_id'],$data); //查詢子節點 } $this -> assign('data',$data); //前端顯示 $this -> display(); echo '<pre>'; print_r($data); } //查詢子節點並返回 function search_children($id,$data){ $children = array(); foreach($data as $one){ if($one['menu_pid'] == $id){ $children[] = $one['menu_id']; } } return $children; } //將數據的鍵名提到數組索引上去 function index_to_key($data,$main_key){ $new_data = array(); foreach($data as $row){ $new_data[$row[$main_key]] = $row; } return $new_data; }
前端代碼:thinkphp
<ul> <foreach name="data" item="v1" key="k1"> <eq name="v1['menu_pid']" value="0"> <li>{$v1.menu_name}</li> <notempty name="v1['children']"> <ul> <foreach name="v1['children']" item="v2" key="k2"> <li>{$data[$v2]['menu_name']}</li> <notempty name="data[$v2]['children']"> <ul> <foreach name="data[$v2]['children']" item="v3" key="k3"> <li>{$data[$v3]['menu_name']}</li> <notempty name="data[$v3]['children']"> <ul> <volist name="data[$v3]['children']" id="v4" key="k4"> <li>{$data[$v4]['menu_name']}</li> </volist> </ul> </notempty> </foreach> </ul> </notempty> </foreach> </ul> </notempty> </eq> </foreach> </ul>
效果:
數組