部落格欄目結構從單層擴展至二級、三級,原本寫死的「首頁 → 欄目名」方式已不適用。需要一個通用方法,根據當前欣目 ID 遞歸查找所有父級,生成完整導航路徑。
category 表關鍵欄位:
catid:欄目 IDcatname:欄目名稱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加入百度地圖,支持周邊標記
now_here 為入口,先寫死首頁連結,查詢當前欄目資料。asmenu != 0),呼叫 get_up_levels 遞歸向上查找。get_up_levels 同樣查詢父級資料,組裝連結,若父級仍有上層則繼續遞歸,並將遞歸結果前置拼接,確保順序為「頂級 → 次級 → 當前」。此方案無需修改資料庫結構,僅靠遞歸邏輯即可支援無限級分類導航,適合 ThinkPHP 3.x 專案快速整合。