首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

ThinkPHP 實現多級欄目與文章當前位置導航(麵包屑)

     編輯:PHP 綜合知識

需求背景

部落格欄目結構從單層擴展至二級、三級,原本寫死的「首頁 → 欄目名」方式已不適用。需要一個通用方法,根據當前欣目 ID 遞歸查找所有父級,生成完整導航路徑。

導航效果圖

資料表結構

category 表關鍵欄位:

  • catid:欄目 ID
  • catname:欄目名稱
  • asmenu:父級欄目 ID,頂級欄目為 0

核心實現:遞歸函數

在控制器中新增兩個 protected 方法:

// 當前位置導航生成
// $catid:當前欄目 ID,$ext:附加文字(如文章標題),欄目導航時留空
protected function now_here($catid, $ext = '') {
    $cat  = M('Category');
    $here = '<a href="https://www.jb51.net">首頁</a>';

    // 取得當前欄目資料
    $uplevels = $cat->field('catid,catname,asmenu')->where("catid=$catid")->find();

    // 遞歸獲取所有父級路徑
    if ($uplevels['asmenu'] != 0) {
        $here .= $this->get_up_levels($uplevels['asmenu']);
    }

    // 附加當前欄目
    $here .= ' -> <a href="/cat_' . $uplevels['catid'] . '.html">' . $uplevels['catname'] . '</a>';

    // 附加額外文字(文章標題等)
    if ($ext != '') {
        $here .= ' -> ' . $ext;
    }
    return $here;
}

// 遞歸向上查找父級欄目
protected function get_up_levels($id) {
    $cat  = M('Category');
    $here = '';
    $uplevels = $cat->field('catid,catname,asmenu')->where("catid=$id")->find();

    $here .= ' -> <a href="/cat_' . $uplevels['catid'] . '.html">' . $uplevels['catname'] . '</a>';

    // 若還有上層,繼續遞歸,並將結果前置(由頂層向下)
    if ($uplevels['asmenu'] != 0) {
        $here = $this->get_up_levels($uplevels['asmenu']) . $here;
    }
    return $here;
}

調用方式

在欄目或文章控制器動作中:

$this->assign('now_here', $this->now_here($catid, $res['title']));
// 欄目頁第二參數傳空字串即可

輸出範例

<a href="https://www.jb51.net">首頁</a> -> 
<a href="/cat_2.html">PHP學習</a> -> 
<a href="/cat_9.html">ecshop</a> -> 
<a href="/cat_13.html">ecshop二次開發</a> -> 
ecshop加入百度地圖,支持周邊標記

原理解析

  1. now_here 為入口,先寫死首頁連結,查詢當前欄目資料。
  2. 若非頂級欄目(asmenu != 0),呼叫 get_up_levels 遞歸向上查找。
  3. get_up_levels 同樣查詢父級資料,組裝連結,若父級仍有上層則繼續遞歸,並將遞歸結果前置拼接,確保順序為「頂級 → 次級 → 當前」。
  4. 最後附加當前欄目與可選的額外文字。

此方案無需修改資料庫結構,僅靠遞歸邏輯即可支援無限級分類導航,適合 ThinkPHP 3.x 專案快速整合。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved