PHP面包屑导航实现原理与概述
本实例演示了如何使用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 "";
foreach($res as $key=>$val) {
echo "{$val['catename']}";
}
echo "";
echo "
";
// 封装方法
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.= "{$v['catename']} > ";
}
return $str;
}
echo displayCatePath(4);
最终在页面上呈现的效果如图所示。

以上便是PHP实现面包屑导航的详细步骤,希望对学习PHP程序设计的朋友有所帮助。