💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
``` // 无限极分类查找下级(递归) 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); } } return $list; } /* * 获得递归完的数据,遍历生成分类 */ $array = getTree($array); //处理样式,进行分级 foreach($array as $value){ echo str_repeat('--', $value['level']), $value['name'].'<br />'; } ``` ``` // 无限极分类查找下级(引用) function generateTree($array){ //第一步 构造数据 $items = array(); foreach($array as $value){ $items[$value['id']] = $value; } //第二部 遍历数据 生成树状结构 $tree = array(); foreach($items as $key => $value){ if(isset($items[$item['pid']])){ $items[$item['pid']]['son'][] = &$items[$key]; }else{ $tree[] = &$items[$key]; } } return $tree; } ``` ~~~ /** * 把返回的数据集转换成Tree(黔南党建项目使用) * @param $list * @param string $pk * @param string $pid * @param string $child * @param string $root * @return array */ public static function listToTree($list, $pk='id', $pid = 'fid', $child = '_child', $root = '0') { $tree = array(); if(is_array($list)) { $refer = array(); foreach ($list as $key => $data) { $refer[$data[$pk]] = &$list[$key]; } foreach ($list as $key => $data) { $parentId = $data[$pid]; if ($root == $parentId) { $tree[] = &$list[$key]; }else{ if (isset($refer[$parentId])) { $parent = &$refer[$parentId]; $parent[$child][] = &$list[$key]; } } } } return $tree; } // 列子: $categoryTree = Tools::listToTree($categoryList, 'id', 'parent_id', 'children'); ~~~ ~~~ public static function formatTree($list, $lv = 0, $title = 'title'){ $formatTree = array(); foreach($list as $key => $val){ $title_prefix = ''; for( $i=0;$i<$lv;$i++ ){ $title_prefix .= "|---"; } $val['lv'] = $lv; $val['namePrefix'] = $lv == 0 ? '' : $title_prefix; $val['showTitle'] = $lv == 0 ? $val[$title] : $title_prefix.$val[$title]; if(!array_key_exists('_child', $val)){ array_push($formatTree, $val); }else{ $child = $val['_child']; unset($val['_child']); array_push($formatTree, $val); $middle = self::formatTree($child, $lv+1, $title); //进行下一层递归 $formatTree = array_merge($formatTree, $middle); } } return $formatTree; } ~~~