php 无限级分类菜单代码 这个
程序的关键就在于数据表的设计很有特色,不用递归,依靠个简单 SQL 语句就能列出菜单,看看这个 数据表怎么
设计的: 数据库字段大概如下: ----------------------------------------------------------------------------------id fid name path 编号 父分类编号 分类名 分类路径,以 id 为节点,组成类似 ,1,2,3,4, 这样的字符串
---------------------------------------------------------------------------------可以假设有如下的数据
id
fid
name 分类 1 分类 2 分类 1-1 分类 1-2 分类 2-1 分类 1-2-1
path
---------------------------------------------------1 2 3 4 5 6 0 0 1 1 2 4 ,1, ,2, ,1,3, ,1,4, ,2,5, ,1,4,6,
---------------------------------------------------这次偷懒, 我只用一个页面, 好在代码不长, 全部代码用类封装的 (不是必要, 而是自己也想熟悉一下 OO, 呵呵!),来看看页面代码: [复制 PHP 代码]
PHP 代码如下:
word) 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<(substr_count($rows['path'],',')-2);$i++) echo '&;nbsp;’; } echo $rows['name'].'
’; } } //创建析构函数,作用:关闭数据库连接 public function __destruct(){ return mysql_close(); } } $db=new menu();//生成实例 $db->menulist();//调用方法生成菜单 ?>