
PHP / MySQL 無需遞歸構建樹形選單
背景:
從資料庫資料中建立樹形選單可以是共同任務。本文探討如何在不使用遞歸的情況下從 PHP 頁面物件陣列建構無序列表 (UL) 選單樹。
數據設置:
您的頁面對像有以下屬性:
- id
- title
- parent_id(根頁面設定為null)
功能概述:
我們將建立一個函數,它接受頁面物件陣列並產生對應的HTML UL 樹。
輔助函數:has_children()
此函數檢查頁面是否有子頁。
1 2 3 4 5 6 7 | <code class = "php" > function has_children( $rows , $id ) {
foreach ( $rows as $row ) {
if ( $row [ 'parent_id' ] == $id )
return true;
}
return false;
}</code>
|
登入後複製
遞歸 Build_Menu() 函數
build_menu() 函數迭代數組並產生 HTML UL 樹。它使用變數 $parent 來追蹤當前父頁面。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <code class = "php" > function build_menu( $rows , $parent =0)
{
$result = "<ul>" ;
foreach ( $rows as $row )
{
if ( $row [ 'parent_id' ] == $parent ){
$result .= "<li>{$row['title']}" ;
if (has_children( $rows , $row [ 'id' ]))
$result .= build_menu( $rows , $row [ 'id' ]);
$result .= "</li>" ;
}
}
$result .= "</ul>" ;
return $result ;
}</code>
|
登入後複製
輸出:
將頁面物件陣列傳遞給 build_menu() 後函數,您可以回顯產生的 HTML UL 樹。輸出將是代表資料庫資料的嵌套 UL 選單結構。
1 | <code class = "php" > echo build_menu( $menu );</code>
|
登入後複製
以上是如何在沒有遞歸的情況下在 PHP/MySQL 中建立樹形選單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!