无限极查找子孙树优化方案

  • 需求
需要将每个员工的部门的全路径循环输入。
  • 问题
当用户量起来的时候,如果使用无限极递归,就会出现超过最大层级256问题和内存溢出等问题。因此,就针对这个问题进行优化。
  • 思路
优化思想:
    第一.避开循环内sql查询(IO开销)
    第二.使用无限极递归放在内存和层级超限。
  • 代码
  • 1 获取所有员工部门全路径
public function getEmployees($company_id){

        //获取该公司下所有部门,并组装需要
        $deptSql = " select id,parent_id,deptName from department where company_id = {$company_id} and status =1 ";
        $deptInfo = DB::select($deptSql);
        
        $allDep = [];
        foreach ($deptInfo as &$value) {
            $allDep[$value->id] = ['id'=>$value->id,'parent_id'=>$value->parent_id,'deptName'=>$value->deptName];
        }
        
        //获取所有员工
        $sql = " select fullName,eid,deptid from employees where company_id = {$company_id}  and del=0 and employees_status<3";
       
        $employees = DB::select($sql);
        
      
        foreach($employees as &$employee){
            //获取部门全路径
            if( $employee->deptid > 0 ){
                $employee->dept_path = self::getFather($allDep,$employee->deptid);
            }
        }
      
      return employees;
}
  • 2.替代递归优化
    /**
     * @param array $arr 部门数组
     * @param integer $id  部门id  默认为顶级
     * @param string $str 部门全路径 默认为空
     * @return string
     */
 public static function getFather($arr, $id=0, $str = '')
{
    //预设计部门层级最大为10层,根据公司需要而定
    for ($i=0; $i < 10; $i++) { 
        if( isset($arr[$id]) ){
            $str .= $arr[$id]['deptName'].'-';
            //非顶级且不是父级的
            if( $arr[$id]['parent_id'] != 0 && $id != $arr[$id]['parent_id'] ){
                $id = $arr[$id]['parent_id'];
            }else{
                break;
            }
        }
    }
    //反转排序
    if(!empty($str)){
        $str = rtrim($str,'-');
        $str = explode('-',$str);
        krsort($str);
        $str = implode('-',$str);
    }
        
    return $str;
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值