php递归获取无限上级ID

数据库结构

CREATE TABLE `fcxlt_authuser` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL COMMENT '用户名',
  `password` varchar(64) NOT NULL COMMENT '密码',
  `nickname` varchar(50) NOT NULL COMMENT '昵称',
  `phone` varchar(20) DEFAULT NULL COMMENT '电话',
  `weixin_id` varchar(20) DEFAULT NULL COMMENT '微信号',
  `qrcode` varchar(200) DEFAULT NULL COMMENT '二维码Base64',
  `auth_id` int(11) NOT NULL,
  `is_authed` int(11) NOT NULL,
  `createtime` int(11) NOT NULL DEFAULT '1523156898',
  PRIMARY KEY (`id`),
  KEY `nickname` (`nickname`),
  KEY `auth_id` (`auth_id`,`id`,`username`,`nickname`) USING BTREE,
  KEY `username` (`username`,`is_authed`,`password`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=utf8mb4

其中auth_id是上级ID,无限分级

递归代码

注意:在引用递归函数本身的时候,一定要return $this->递归函数,否则返回NULL

public function getWinfo($id,$res=''){
        if($id>1){
            $infos = Db::name('authuser')
                ->alias('a')
                ->where('a.id',$id)
                ->join('fcxlt_authuser b', 'a.auth_id=b.id', 'LEFT')
                ->field('a.auth_id as id')
                ->find();
//        dump($infos);
            if(!empty($infos) && $infos['id']>1){
                $res.= $infos['id'].",";
                return $this->getWinfo($infos['id'],$res);
            }else{
                return $res;
            }
        }else{
            return $res;
        }

    }

控制器调用

$ids = $this->getWinfo($id,$res=$id.',');
$id_in =  substr($ids,0,strlen($ids)-1);
$id_arr = explode(',',$id_in);
发布了62 篇原创文章 · 获赞 11 · 访问量 8097

猜你喜欢

转载自blog.csdn.net/u013252962/article/details/99735588