夺命雷公狗---无限级分类NO3
<?php header("Content-Type:text/html;charset=utf-8"); /* 无限级分类。牵扯2个应用 0是-找指定栏目的子栏目 1是-找指定栏目的子孙栏目,即子孙树 2是-找指定栏目的父栏目/父父栏目....顶级栏目,即家谱树 */ $aarr = array( array('id'=>1,'name'=>'安徽','pid'=>0), array('id'=>2,'name'=>'海淀','pid'=>7), array('id'=>3,'name'=>'浣溪县','pid'=>5), array('id'=>4,'name'=>'昌平','pid'=>7), array('id'=>5,'name'=>'淮北','pid'=>1), array('id'=>6,'name'=>'朝阳','pid'=>7), array('id'=>7,'name'=>'北京','pid'=>0), array('id'=>8,'name'=>'上地','pid'=>2) ); function subtree($arr,$id=0,$lev=1){ $subs = array(); //子孙树 foreach($arr as $v){ if($v['pid'] == $id){ $v['lev'] = $lev; $subs[] = $v; $subs = array_merge($subs,subtree($arr,$v['id'],$lev+1));//array_merge让数组粘起来 } } return $subs; } $tree = subtree($aarr,0,1); foreach($tree as $v){ echo str_repeat(' ',$v['lev']).$v['name'].'<br/>';//str_repeat替换 }