多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
``` /** * 数组转树结构 * @param $list * @param $pk 当前节点 * @param $pid 父节点 * @param string $child 孩子节点 * @return array */ static function arrayToTree($list, $pk, $pid, $child = 'children') { $tree = array(); if (!is_array($list)) { return $tree; } $refer = array(); $parentNodeIdArr = []; foreach ($list as $key => $data) { $refer[$data[$pk]] = &$list[$key]; $parentNodeIdArr[$data[$pid]] = $data[$pid]; } /* 寻找根结点 */ foreach ($list as $key => $data) { if (in_array($data[$pk], $parentNodeIdArr)) { unset($parentNodeIdArr[$data[$pk]]); } } foreach ($list as $key => $data) { $parantId = $data[$pid]; if (in_array($parantId, $parentNodeIdArr)) { $tree[] = &$list[$key]; } else { if (isset($refer[$parantId])) { $parent = &$refer[$parantId]; $parent[$child][] = &$list[$key]; } } } return $tree; } ``` ``` /** * service层调用 * @param array $where * @return array */ public function getMenuTree($where = null){ // 把所有的栏目都查出来 $list = (new AdminMenu())->getByWhere($where)->toArray(); // 把数据转成树结构 return TreeUtil::arrayToTree($list,'id','pid'); } ``` ``` //调用前结果 array(114) { [0] => array(8) { ["id"] => int(1) ["pid"] => int(0) ["title"] => string(12) "系统管理" ["icon"] => string(8) "icon-set" ["sort"] => int(1) ["url"] => string(13) "Setting/index" ["url_type"] => string(6) "栏目" ["url_param"] => NULL } [1] => array(8) { ["id"] => int(5) ["pid"] => int(1) ["title"] => string(12) "系统配置" ["icon"] => string(11) "icon-set-sm" ["sort"] => int(1) ["url"] => string(13) "Setting/index" ["url_type"] => string(6) "栏目" ["url_param"] => NULL } [2] => array(8) { ["id"] => int(7) ["pid"] => int(2) ["title"] => string(12) "角色列表" ["icon"] => string(9) "icon-user" ["sort"] => int(1) ["url"] => string(10) "Role/index" ["url_type"] => string(6) "栏目" ["url_param"] => NULL } //调用后结果 array(10) { [0] => array(9) { ["id"] => int(1) ["pid"] => int(0) ["title"] => string(12) "系统管理" ["icon"] => string(8) "icon-set" ["sort"] => int(1) ["url"] => string(13) "Setting/index" ["url_type"] => string(6) "栏目" ["url_param"] => NULL ["children"] => array(1) { [0] => array(9) { ["id"] => int(5) ["pid"] => int(1) ["title"] => string(12) "系统配置" ["icon"] => string(11) "icon-set-sm" ["sort"] => int(1) ["url"] => string(13) "Setting/index" ["url_type"] => string(6) "栏目" ["url_param"] => NULL ["children"] => array(1) { [0] => array(8) { ["id"] => int(12) ["pid"] => int(5) ["title"] => string(13) "操作-修改" ["icon"] => string(0) "" ["sort"] => int(1) ["url"] => string(11) "Setting/add" ["url_type"] => string(6) "操作" ["url_param"] => NULL } } } } } ```