概述
在实际工作中,经常要用到无限极分类。如导航表等等。到网上一搜php无限极分类,很多,但好多都是一个,并且,写的很乱,代码很多,那些都不靠谱,还是自己捣鼓捣鼓无限极分类了。下面介绍两种无限极分类:递归
,使用引用
数据准备
//初始化原始数据(id=>编号,name=>显示名称,pid=>父级目录id,sort=>排序顺序)
$data[1] = array('id'=>'1','name'=>'一级目录A','pid'=>'0','sort'=>'1');
$data[2] = array('id'=>'2','name'=>'一级目录B','pid'=>'0','sort'=>'2');
$data[3] = array('id'=>'3','name'=>'一级目录C','pid'=>'0','sort'=>'3');
$data[4] = array('id'=>'4','name'=>'一级目录D','pid'=>'0','sort'=>'4');
$data[5] = array('id'=>'5','name'=>'二级目录A-1','pid'=>'1','sort'=>'1');
$data[6] = array('id'=>'6','name'=>'二级目录A-2','pid'=>'1','sort'=>'2');
$data[7] = array('id'=>'7','name'=>'二级目录A-3','pid'=>'1','sort'=>'3');
$data[8] = array('id'=>'8','name'=>'二级目录B-1','pid'=>'2','sort'=>'1');
$data[9] = array('id'=>'9','name'=>'二级目录B-2','pid'=>'2','sort'=>'2');
$data[10] = array('id'=>'10','name'=>'二级目录B-3','pid'=>'2','sort'=>'3');
$data[11] = array('id'=>'11','name'=>'二级目录C-1','pid'=>'3','sort'=>'2');
$data[12] = array('id'=>'12','name'=>'二级目录D-1','pid'=>'4','sort'=>'1');
$data[13] = array('id'=>'13','name'=>'二级目录D-2','pid'=>'4','sort'=>'2');
$data[14] = array('id'=>'14','name'=>'三级目录A-2-1','pid'=>'6','sort'=>'1');
$data[15] = array('id'=>'15','name'=>'三级目录A-2-2','pid'=>'6','sort'=>'2');
$data[16] = array('id'=>'16','name'=>'三级目录C-1-1','pid'=>'11','sort'=>'1');
$data[17] = array('id'=>'17','name'=>'三级目录B-2-1','pid'=>'9','sort'=>'2');
先写一个显示树结构的函数
function printTree($data,$level=0){
foreach($data as $key=>$value){
for($i=0;$i<=$level;$i++){
echo '  ';
}
echo $value['name'];
echo '<br>';
if(!empty($value['children'])){
printTree($value['children'],$level+1);
}
}
}
递归-无限极分类
使用递归的方式获取无限极分类数组
function getNodeTree(&$list,&$tree,$pid=0){
foreach($list as $key=>$value){
if($pid == $value['pid']){
$tree[$value['id']]=$value;
unset($list[$key]);
getNodeTree($list,$tree[$value['id']]['children'],$value['id']);
}
}
}
使用引用-无限极分类
function createNodeTree(&$list,&$tree){
foreach($list as $key=>$node){
if(isset($list[$node['pid']])){
$list[$node['pid']]['children'][] = &$list[$key];
}else{
$tree[] = &$list[$node['id']];
}
}
}
果然是厉害,代码简洁精炼,无需递归,执行速度快。这是我偶然在一个网站上看到的,觉得很实用就收藏下来,分享给大家。
网站地址为:http://www.phpddt.com/php/generateTree.html
调用
//递归-无限极分类调用
getNodeTree($data,$tree);
printTree($tree);
//使用引用-无限极分类调用
createNodeTree($data,$tree);
printTree($tree);