|
在寫多層導覽列時,會從資料庫撈出資料
主要欄位有
cid,parent_id,name
以下是PHP代碼
- //從TABLE撈出資料
- $sql="SELECT * FROM net_class ORDER BY cid ASC";
- $query=$db->query($sql);
- while ($row_class=$db->fetch_array($query)) {
- //放入陣列 $sm_class[]=array("cid"=>$row_class[cid],"num"=>$row_class[num],"name"=>$row_class[name],"img"=>$row_class[img],"parent_id"=>$row_class[parent_id]);
- }
- function has_children($rows,$cid) {
- foreach ($rows as $rowf) {
- if ($rowf['parent_id'] == $cid)
- return true;
- }
- return false;
- }
-
- function build_menu($rows,$parent=0)
- {
- $result = "<ul>";
- foreach ($rows as $row)
- {
- if ($row['parent_id'] == $parent){
- $result.= "<li>{$row[name]}";
- if (has_children($rows,$row['cid']))
- $result.= build_menu($rows,$row['cid']);
- $result.= "</li>";
- }
- }
- $result.= "</ul>";
- return $result;
- }
- echo build_menu($sm_class);
複製代碼
經過筆者實測,此種多重選單最為簡單明白
或是- function buildTree(array $elements, $parentId = 0) {
- $branch = array();
- foreach ($elements as $element) {
- if ($element['parent_id'] == $parentId) {
- $children = buildTree($elements, $element['id']);
- if ($children) {
- $element['children'] = $children;
- }
- $branch[] = $element;
- }
- }
- return $branch;
- }
- $tree = buildTree($rows);
複製代碼
參考文章
http://stackoverflow.com/questio ... sql-build-tree-menu
http://stackoverflow.com/questio ... rom-database-result
|
|