今天分享下自己学习细说php中的无限分类方法。

php无限分类大致有三种方式,

  1、数据库通过设置父类ID来进行唯一索引,然后使用函数的递归调用实现无限分类;

  2、数据库设计通过特定格式进行排列,然后使用mysql查询关键函数:concat。程序实现比较简单;

  3、第三种不是太了解, 好像要使用到算法和数据结构进行排列。

今天我主要分享下第二种方式,一开始也是找了很多资料,确实比较难理解。不过最终还是给搞明白了,因此记下随笔,希望通过这篇文章能够帮助到大家。

一、数据库设计:

  

 1 --
2 -- Table structure for table `category`
3 --
4
5 CREATE TABLE IF NOT EXISTS `category` (
6 `id` int(11) NOT NULL AUTO_INCREMENT,
7 `catpath` varchar(255) DEFAULT NULL,
8 `name` varchar(255) DEFAULT NULL,
9 PRIMARY KEY (`id`)
10 ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;
11
12 --
13 -- Dumping data for table `category`
14 --
15
16 INSERT INTO `category` (`id`, `catpath`, `name`) VALUES
17 (1, '0', '网站首页'),
18 (2, '0-1', 'Linux OS'),
19 (3, '0-1', 'Apache服务器'),
20 (4, '0-1', 'MySQL数据库'),
21 (5, '0-1', 'PHP脚本语言'),
22 (6, '0-1-2', 'Linux 系统教程'),
23 (7, '0-1-2', 'Linux 网络技术'),
24 (8, '0-1-2', 'Linux 安全基础'),
25 (9, '0-1-2-7', 'Linux LAMP'),
26 (10, '0-1-3-10', 'apache Server');

  

这里说明下,catpath的-链接符号不是固定的,可以选择,;等特殊符号。

二、 PHP代码实现:

    

 1 $conn = mysql_connect ( 'localhost', 'root', '' );
2 mysql_select_db ( 'test', $conn );
3 mysql_query ( 'set names UTF8' );
4 $sql = "select id,concat(catpath,'-',id) as abspath,name from category order by abspath";
5 $query = mysql_query ( $sql );
6 while ( $row = mysql_fetch_array ( $query ) ) {
7 /**
8 * 第一种展示方法
9 */
10 /*$space = str_repeat ( '    ', count ( explode ( '-', $row ['abspath'] ) ) - 1 );
11 echo $space . $row ['name'] . '<br>';*/
12 /**
13 * 第二种展示方法
14 */
15 $space = str_repeat ( '&nbsp;&nbsp;&nbsp;&nbsp;', count ( explode ( '-', $row ['abspath'] ) ) - 1 );
16 $option .= '<option value="' . $row ['id'] . '">' . $space . $row ['name'] . '</option>';
17 }
18 echo '<select name="opt">' . $option . '</select>';

上效果图:

    

这里有几个关键的地方需要注意下:

 1、在数据库查询字段是用了concat函数,不了解的地方可以google下。 

 2、第二个地方主要是用到了php中的str_repeat巧妙的设置了空格。

有错误之处,望mail: chenghuiyong1987@gmail.com或者留言

作者: Brave Cheng 发表于 2011-08-26 08:58 原文链接

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"