Home >Backend Development >PHP Tutorial >PHP Infinitus Classification_PHP Tutorial
php Infinitus Classification is often used. I have always used the ones that have been written before, so I have not studied it carefully. Today, due to To meet the needs of the project, I needed to make a temporary PHP Infinitus classification stuff, so I made the simplest one. The record is as follows. Friends in need can take a look.
Data table structure
CREATE TABLE IF NOT EXISTS `category` ( `id` int(5) NOT NULL AUTO_INCREMENT COMMENT '唯一自增id', `pid` int(5) NOT NULL DEFAULT '0' COMMENT '父id', `sort` int(2) NOT NULL DEFAULT '0' COMMENT '排序数字', `name` varchar(30) DEFAULT NULL COMMENT '名称', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='无限极分类表' AUTO_INCREMENT=1 ;
Data
INSERT INTO `category` (`id`, `pid`, `sort`, `name`) VALUES (1, 0, 1, 'php'), (2, 0, 2, '数据库'), (3, 0, 3, 'javascript'), (4, 1, 1, '框架模板'), (5, 1, 2, '函数总结'), (6, 2, 1, 'mysql'), (7, 4, 1, '框架'), (8, 4, 2, '模板'), (9, 8, 1, 'smarty'), (10, 7, 2, 'thinkphp'), (11, 10, 1, 'thinkphp技巧'), (12, 10, 2, 'thinkphp模板'), (13, 12, 3, '模板知识总结'), (14, 12, 2, '模板视频教程'), (15, 11, 1, 'model技巧');
Function implementation code
function tree(&$list,$pid=0,$level=0,$html='--'){ static $tree=array(); foreach($list as $v){ if($v['pid']==$pid){ $v['level']=$level; $v['html']=str_repeat($html,$level); $tree[]=$v; tree($list,$v['id'],$level+1,$html); } } return $tree; }
The first parameter $list of the above tree function is the obtained result set of a two-dimensional array as shown in the table above. It should be noted that the sql statement to obtain the result set from the database must be added with order by sort asc, otherwise the sort field will not be able to play a sorting role .