首先要感谢terry39的指点,元旦闲来无事,我就把他所讲的原理简单实现一下,这个程序的关键就在于数据表的设计很有特色,不用递归,依靠个简单SQL语句就能列出菜单,看看这个数据表怎么设计的:
数据库字段大概如下:
-----------------------------------------------------------------------------------
id 编号
fid 父分类编号
name 分类名
path 分类路径,以 id 为节点,组成类似 ,1,2,3,4, 这样的字符串
----------------------------------------------------------------------------------
可以假设有如下的数据
id fid name path
----------------------------------------------------
1 0 分类1 ,1,
2 0 分类2 ,2,
3 1 分类1-1 ,1,3,
4 1 分类1-2 ,1,4,
5 2 分类2-1 ,2,5,
6 4 分类1-2-1 ,1,4,6,
----------------------------------------------------
这次偷懒,我只用一个页面,好在代码不长,全部代码用类封装的(不是必要,而是自己也想熟悉一下OO,呵呵!),来看看页面代码:
复制代码 代码如下:
/**************************************
页面:menu.php
作者:辉老大
功能:定义数据库操作及生成菜单列表类
**************************************/
class menu{
//创建构造函数,作用:数据库连接并选择相应数据库
public function __construct(){
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "7529639";
$dbname = "menu";
mysql_connect($dbhost,$dbuser,$dbpassword) or die("error!");
mysql_query("SET NAMES 'GBK'");
mysql_select_db($dbname);
}
//执行SQL语句函数
private function query($sql){
return mysql_query($sql);
}
//取得结果集数组函数
private function loop_query($result){
return mysql_fetch_array($result);
}
//列出菜单列表函数
public function menulist(){
$sql="select * from list order by path";
$result=$this->query($sql);
while($rows=$this->loop_query($result)){
if(substr_count($rows['path'],',')>2){
for($i=0;$i echo ' ';
}
echo $rows['name'].'
';
}
}
//创建析构函数,作用:关闭数据库连接
public function __destruct(){
return mysql_close();
}
}
$db=new menu();//生成实例
$db->menulist();//调用方法生成菜单
?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor