本執行個體講解了php實現麵包屑導航的方法,麵包屑導航在項目非常實用,在此處就寫一個這方面的實現。
path表示所有的祖先id,fullpath表示所有的祖先id和本身id
---- 表的結構 `tp_likecate`--CREATE TABLE IF NOT EXISTS `tp_likecate` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `catename` varchar(24) NOT NULL, `path` varchar(10) NOT NULL, `fullpath` varchar(20) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;
資料
---- 轉存表中的資料 `tp_likecate`--INSERT INTO `tp_likecate` (`id`, `catename`, `path`, `fullpath`) VALUES(1, '手機', '', ',1'),(2, '功能手機', '1', '1,2'),(3, '老人手機', '1,2', '1,2,3'),(4, '兒童手機', '1,2', '1,2,4'),(5, '智能手機', '1', '1,5'),(6, 'android手機', '1,5', '1,5,6'),(7, 'IOS手機', '1,5', '1,5,7'),(8, 'WinPhoto手機', '1,5', '1,5,8');
資料庫連接:
<?php $db_host = 'localhost';$db_user = 'root';$db_password = '';$db_name = 'test';$con = mysql_connect($db_host, $db_user, $db_password) or die(mysql_error());mysql_select_db($db_name, $con) or die(mysql_error());mysql_query('set names utf8') or die(mysql_error());?>
主函數:
function likecate($path='') { // concat() 串連欄位 $sql = "select id,catename,path, concat(path,',',id) as fullpath from tp_likecate order by fullpath asc"; $res = mysql_query($sql); $result = array(); while($row=mysql_fetch_assoc($res)) { $deep = count(explode(',', trim($row['fullpath'], ','))); // explode字串轉換為數組 implode數群組轉換為字串 $row['catename'] = @str_repeat(' ', $deep).'|--'.$row['catename']; $result[] = $row; } return $result;}
輸出:
// 簡單輸出$res = likecate();echo "<select name='cate'>";foreach($res as $key=>$val) { echo "<option>{$val['catename']}</option>";}echo "</select>";echo "<br />";// 封裝方法function getPathCate($cateid) { $sql = "select *,concat(path, ',',id) fullpath from tp_likecate where id = $cateid"; $res = mysql_query($sql); $row = mysql_fetch_assoc($res); $ids = $row['fullpath']; $sql = "select * from tp_likecate where id in($ids) order by id asc"; $res = mysql_query($sql); $result = array(); while($row = mysql_fetch_assoc($res)) { $result[] = $row; } return $result;}// 加上了連結的參數function displayCatePath($cateid,$link='cate.php?cid=') { // 也可以組裝 $res = getPathCate($cateid); $str = ''; foreach($res as $k=>$v) { $str.= "<a href='{$link}{$v['id']}'>{$v['catename']}</a> > "; } return $str;}echo displayCatePath(4);
效果:
以上就是php實現麵包屑導航的詳細步驟,希望對大家學習php程式設計有所協助。