thinkphp實現麵包屑導航(當前位置)例子分享_PHP教程

來源:互聯網
上載者:User
以前欄目很少,就用死辦法做的(首頁 -> 欄目的名字),現在欄目多了,漸漸二級欄目,三級欄目也來了,這樣的方式顯然不太合適,於是就改進了一下。也不難,利用一個遞迴函式就可以了。

使用例子:

複製代碼 代碼如下:
//當前位置-第一個參數 catid為當前欄目的id,第二個參數為文章的標題,調用欄目當前位置時第二個參數為空白即可。
$this->assign("now_here",$this->now_here($catid,$res['title']));

實現代碼:

複製代碼 代碼如下:

//解釋一下,欄目表category中的catid為欄目id,catname為欄目名稱,asmenu為欄目父級的id,當為頂級欄目時,asmenu為0 。
protected function now_here($catid,$ext=''){
$cat = M("Category");
$here = '首頁';
$uplevels = $cat->field("catid,catname,asmenu")->where("catid=$catid")->find();
if($uplevels['asmenu'] != 0)
$here .= $this->get_up_levels($uplevels['asmenu']);
$here .= ' -> '.$uplevels['catname']."";
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 .= ' -> '.$uplevels['catname']."";
if($uplevels['asmenu'] != 0){
$here = $this->get_up_levels($uplevels['asmenu']).$here;
}
return $here;
}


附:另一個例子

複製代碼 代碼如下:
class IndexAction extends Action {

public function cat() {
load('extend'); // 載入 extend.php 檔案
// 取出所有的分類
$Categories = M('Categories')->select();

$nav_array = array();
$this->getNavCrumbs($Categories, 2120, $nav_array);
dump($nav_array);

// 取出所有分類(並構造成一棵樹)
// $CategoryTree = list_to_tree($Categories, 'categories_id', 'parent_id');
}

/**
* 根據分類id向上回溯構造麵包屑
* @param $Categories 由所有分類組成的數組
* @param $categoryId 要進行向上回溯用的分類id
* @param $navCrumbs 用於儲存結果的數組,傳入一個空數組就好
*/
public function getNavCrumbs($Categories, $categoryId, &$navCrumbs) {
$category = list_search( $Categories, array('categories_id'=>$categoryId) ) ;
$category = $category[0];
$parent_id = $category['parent_id'];
$categories_id = $category['categories_id'];

if( $parent_id != 0 ) { // 這裡的 0 是根節點id(root節點id)
$this->getNavCrumbs($Categories, $parent_id, $navCrumbs);
}

$navCrumbs[$categories_id] = $category;
}

}


http://www.bkjia.com/PHPjc/768136.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/768136.htmlTechArticle以前欄目很少,就用死辦法做的(首頁 - 欄目的名字),現在欄目多了,漸漸二級欄目,三級欄目也來了,這樣的方式顯然不太合適,於是...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.