ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
``` /** * $list 为查询 出来的二维数组 **/ public function getTree($list,$pid=0,$itemprefix = '') { static $icon = array('│', '├', '└'); static $nbsp = " "; static $arr = array(); $number = 1; foreach($list as $row) { if($row['pid'] == $pid) { $brotherCount = 0; //判断当前有多少个兄弟分类 foreach($list as $r) { if($row['pid'] == $r['pid']) { $brotherCount++; } } if($brotherCount >0) { $j = $k = ''; if($number == $brotherCount) { $j .= $icon[2]; $k = $itemprefix ? $nbsp : ''; }else{ $j .= $icon[1]; $k = $itemprefix ? $icon[0] : ''; } $spacer = $itemprefix ? $itemprefix . $j : ''; $row['name'] = $spacer.$row['name']; $arr[] = $row; $number++; $this->getTree($list,$row['id'],$itemprefix . $k . $nbsp); } } } return $arr; } ``` ## 树形结构 ~~~ function listTreeIntelligence($list, $pk='id', $pid = 'pid', $child = 'child', $root = 0) { // 创建Tree $tree = array(); if (is_array($list)) { //创建基于主键的数组引用 $refer = array(); foreach ($list as $key => $data) { $refer[$data[$pk]] = &$list[$key]; } $ids = array_map(function($item) use($pk){ return $item[$pk]; },$list); foreach ($list as $key => $data) { // 判断是否存在parent $parantId = $data[$pid]; if ($root == $parantId || !in_array($parantId, $ids)) { $tree[] = &$list[$key]; } else { if (isset($refer[$parantId])) { $parent = &$refer[$parantId]; $parent[$child][] = &$list[$key]; } } } } return $tree; } ~~~