PHP-无限级分类
给定省市地区数组如下:
$area = array(
array('id'=>1,'name'=>'安徽','parent'=>'0'),
array('id'=>2,'name'=>'海淀','parent'=>'7'),
array('id'=>3,'name'=>'濉溪县','parent'=>'5'),
array('id'=>4,'name'=>'昌平','parent'=>'7'),
array('id'=>5,'name'=>'淮北','parent'=>'1'),
array('id'=>6,'name'=>'朝阳','parent'=>'7'),
array('id'=>7,'name'=>'北京','parent'=>'0'),
array('id'=>8,'name'=>'上地','parent'=>'2')
);
无限级分类的应用有如下几种:
1、找指定栏目的子栏目
2、找指定栏目的子孙栏目--子孙树
3、找指定栏目的父栏目/父父栏目....------家谱树
#找指定栏目的子栏目#
function sontree($arr,$id=0){//默认从顶级栏目开始找 $son = array(); foreach($arr as $v){ if($v['parent'] == $id){ $son[] = $v; } } return $sons; } echo '<pre>'; print_r(sontree($area,0)); echo'</pre>';
#找指定栏目的子孙栏目--子孙树#
function substree($arr,$id=0,$jibie=0){ $tree = array(); foreach($arr as $v){ if($v['parent'] == $id){ $tree[] = $v; $v['jibie'] = $jibie; $tree = array_merge($tree,subtree($arr,$v['id']),$jibie+1); } return $tree; } } echo '<pre>'; print_r(substree($area,0)); echo'</pre>';
//真实案例:部门职工树
private function _deptspns($lv,$pid){ $db = m('dept'); $s = ''; $r = m('admin')->getone("id='".$this->adminid."'",'type,deptid'); if($r['type']==0)$s = ' and id=\''.$r['deptid'].'\''; $rows = $db->getall(" `pid`='".$pid."' $s order by `sort`",'*'); $da = array(); if(count($rows)){ foreach($rows as $k=>$mv){ $da[$k] = array( 'id'=>$mv['id'], 'lv'=>$lv, 'name'=>$mv['name'], 'pid'=>$mv['pid'], 'expanded'=>true ); $da[$k]['children'] = $this->_deptspns($lv+1,$mv['id']); } } return $da; } $da = $this->_deptspns(1,0);
//方法二(static)
function substree($arr,$id=0,$jibie=0){ static $tree = array(); foreach($arr as $v){ if($v['parent'] == $id){ $v['jibie'] = $jibie; $tree[] = $v; subtree($arr,$v['id']),$jibie+1); } return $tree; } } echo '<pre>'; print_r(substree($area,0)); echo'</pre>';
#家谱树#
//方法一
function parenttree($arr,$id=0){ $par = array(); foreach($arr as $v){ if($v['id'] == $id) { if($v['parent'] > 0){ //如果为0就是顶级 它没有父栏目.... array_merge($par,parenttree($arr,$v['[parent'])); $par[] = $v;//第一次把自己存入 /*把$par[] = $v;/写在后面 array_merge($par,parenttree($arr,$v['[parent']));就是先进后出 结果可以是:北京-》海淀-》上地 写在前面结果相反 递归递归-先递在归 */ } } } return $par; } echo '<pre>'; print_r(parenttree($area,0)); echo '</pre>';
方法二:
function parenttree($arr,$sid=0,$jibie=1){ static $parent = array(); static $pid = null; foreach($arr as $val){ if($sid == $val['id']){ $pid = $val['parent']; //$parent[] = $val; } } foreach($arr as $val1){ if($pid == $val1['id']){ $val1['jibie'] = $jibie; $parent[] = $val1; parenttree($arr,$pid,$jibie+1); } } return $parent; } echo '<pre>'; print_r(parenttree($area,8,1)); echo '</pre>'; exit; $parent_arr = parenttree($area,8,1); foreach($parent_arr as $val){ echo @str_repeat('      ',$val['jibie']),$val['name'],'<br/>'; } /* 经过测试这个方法我只求出了它的父亲以上的栏目,它自己没有存入,也请大家帮忙修改 这个方法造成的缺陷就是在例如面包屑导航条上有bug */
有耕耘、有搬运、共学习