您好,欢迎访问一九零五行业门户网

php 无限分类实现原理详解

在php中无限分类是我们在实际开发中经常用到的一种数据结构,一般我们称之为树形结构,像我网站的分类有php入门,正则等等分类,这种是二级不是无限级了,如果是无限级就可以在子类下加子类了.
我们先来看我实现无限分类的具体过程.
题设:类似淘宝的商品分类,可以在任意分类设置其子类.
一、创建`type`数据表,代码如下:
`id` 自增长 `fid` int(11) 默认(0) ,父节点id `name` varchar(50),分类名称 create table `type` ( `id` int(11) not null auto_increment, `fid` int(11) not null default '0', `name` varchar(50) not null, primary key (`id`) )
二、添加,我们先添加几个顶级分类,代码如下:
insert into `type` (`id`, `fid`, `name`) values (null, '0', '手机'); insert into `type` (`id`, `fid`, `name`) values (null, '0', '电脑'); insert into `type` (`id`, `fid`, `name`) values (null, '0', '鞋子'); insert into `type` (`id`, `fid`, `name`) values (null, '0', '衣服');这里fid=0是代表顶级分类
接着我们为{电脑}添加几个个子分类,代码如下:
insert into `type` (`id`, `fid`, `name`) values (null, '2', '台式'), (null, '2', '笔记本');
这里fid=2,2这个id是分类{电脑}的id,如果是添加{鞋子}的子分类则fid=3,同理我们为{笔记本}添加子分类则fid=6,代码如下:
insert into `type` (`id`, `fid`, `name`) values (null, '6', 'ausu'), (null, '6', 'hp');
三、删除,如果我们想删除{笔记本}这个分类,很简单:
delete from `type` where `id`=6{笔记本}的子分类我们也要记得做相应的处理
代码如下:
0 ), array( 'id' => 2, 'name' => 'php', 'parentid' => 1 ), array( 'id' => 3, 'name' => 'smarty', 'parentid' => 2 ), array( 'id' => 4, 'name' => 'life', 'parentid' => 0 ), array( 'id' => 5, 'name' => 'pdo', 'parentid' => 2 ), array( 'id' => 6, 'name' => 'pdo-mysql', 'parentid' => 5 ), array( 'id' => 7, 'name' => 'java', 'parentid' => 1 ) ); // 72648 // 84072 function findchild(&$arr,$id){ $childs=array(); foreach ($arr as $k => $v){ if($v['parentid']== $id){ $childs[]=$v; } } return $childs; } function build_tree($root_id){ global $rows; $childs=findchild($rows,$root_id); if(emptyempty($childs)){ return null; } foreach ($childs as $k => $v){ $rescurtree=build_tree($v[id]); if( null != $rescurtree){ $childs[$k]['childs']=$rescurtree; } } return $childs; } $tree=build_tree(0); echo memory_get_usage(); print_r($tree); ?>
我自己用的可以做那种下拉效果并带有级数的效果,代码如下:

$fenlei 无限分类数组 $id是选择从哪个分类开始写0代表顶级开始分,只要把数组放进去就可以分了.
永久链接:
转载随意!带上文章地址吧。
其它类似信息

推荐信息