无限级分类的一种实现方式
程序员文章站
2022-06-29 08:09:47
如果只需要所有层级名称 //获取所有子孙 ......
list返回子孙树列表
1 /** 2 * * list返回子孙树 3 * @param array $list 原始列表 4 * @param int $parentid 父id 5 * @param int $level 几级子孙 6 * @param string $space 空格占位 7 * @date:2017.2.17 8 * @return array 9 */ 10 function treelist($list, $parentid = 0, $level = 0, $space = ' ') 11 { 12 static $bk = array(); 13 foreach ($list as $each) 14 { 15 if ($each['parent_id'] == $parentid) 16 { 17 $each['level'] = $level; 18 $each['show'] = str_repeat($space, $level) . $each['name']; 19 $bk[$each['id']] = $each; 20 treelist($list, $each['id'], $level + 1, $space);//子孙紧跟在自己后面 21 } 22 } 23 return $bk; 24 }
list返回子孙树数组
1 /** 2 * * list返回子孙树 3 * @param array $list 原始列表 4 * @param int $parentid 父id 5 * @param int $level 几级子孙 6 * @param string $space 空格占位 7 * @date:2017.2.17 8 * @return array 9 */ 10 function treearr($list, $parentid = 0, $level = 0, $space = ' ') 11 { 12 $bk = array(); 13 foreach ($list as $each) 14 { 15 if ($each['parent_id'] == $parentid) 16 { 17 $each['level'] = $level; 18 $each['show'] = str_repeat($space, $level) . $each['name']; 19 $each['sonarr'] = treearr($list, $each['id'], $level + 1, $space); 20 $bk[$each['id']] = $each; 21 } 22 } 23 return $bk; 24 }
如果只需要所有层级名称
/** * 获取所有层级名列表 * @date:2017.2.17 * @return array */ function getfulnamelist() { $listraw = getlist(); $list = array(); //一些处理 foreach ($listraw as $each) { $list[$each['id']] = iconvarray($each, 'gbk', 'utf-8');//gbk->utf-8 } //加所有层级名 foreach ($list as $id => $each) { $fulname = $list['name']; $parentid = $each['parent_id']; while ($parentid != 0 && $list[$parentid]['parent_id'] != 0) { $fulname = $list[$parentid]['name'].'_'.$fulname; $parentid = $list[$parentid]['parent_id']; } $list[$id]['fulname'] = $fulname; } return $list; }
//获取所有子孙
1 function getspringid($selfid, $list) 2 { 3 $springidarr = array(); 4 $parentidarr = array($selfid => $selfid); 5 do 6 { 7 $newsonarr = array(); 8 foreach ($list as $each) 9 { 10 if (isset($parentidarr[$each['parent_id']])) 11 { 12 $springidarr[$each['id']] = $each['id']; 13 $newsonarr[$each['id']] = $each['id']; 14 } 15 } 16 $parentidarr = $newsonarr;//新一辈父 17 } while (count($parentidarr) > 0); 18 19 return $springidarr; 20 }
上一篇: 第四章爬虫进阶之图形验证码识别技术
下一篇: 做龙虾调料都需要哪些,爱吃的你不要错过哦