初始化的数据
//初始化原始数据(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 '&emsp&emsp'} 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']]
}
}
}
调用
//递归-无限极分类调用getNodeTree($data,$tree)printTree($tree)//使用引用-无限极分类调用createNodeTree($data,$tree)
printTree($tree)
/*** 递归实现无限极分类
* @param $array 分类数据
* @param $pid 父ID
* @param $level 分类级别
* @return $list 分好类的数组 直接遍历即可 $level可以用来遍历缩进
*/
function getTree($array, $pid =0, $level = 0){
//声明静态数组,避免递归调用时,多次声明导致数组覆盖
static $list = [] foreach ($array as $key => $value){ //第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
if ($value['pid'] == $pid){ //父节点为根节点的节点,级别为0,也就是第一级
$value['level'] = $level //把数组放到list中
$list[] = $value //把这个节点从数组中移除,减少后续递归消耗
unset($array[$key]) //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
getTree($array, $value['id'], $level+1)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)