无限级关系带层级

一、创建表

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `test`
-- ----------------------------
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `pid` int(10) NOT NULL COMMENT '父ID',
  `name` varchar(10) NOT NULL COMMENT '姓名',
  `mobile` varchar(11) NOT NULL COMMENT '手机号',
  PRIMARY KEY (`id`),
  KEY `PID` (`pid`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='无限分级测试';

-- ----------------------------
-- Records of test
-- ----------------------------
INSERT INTO `test` VALUES ('1', '0', 'lee01', '');
INSERT INTO `test` VALUES ('2', '1', 'lee02', '');
INSERT INTO `test` VALUES ('3', '2', 'lee03', '');
INSERT INTO `test` VALUES ('4', '2', 'lee04', '');
INSERT INTO `test` VALUES ('5', '3', 'lee05', '');

核心点: id、pid

二、代码

//递归测试
    public function recursionTest(){
        $pid=0; //父ID
        //先获取全部相关数据
        $data=$this->getData($pid);
//        dump($data);
        //重新排序
        $res=$this->getTree($data,$pid);
        dump($res);
    }

    //根据id获得全部数据 无排序
    public function getData($pid){
        static $arr=array();
        $data=db('test')->where("pid =".$pid)->select();
        if($data){
            foreach($data as $k=>$v){
                $arr[]=$v;
                $this->getData($v['id']);
            }
        }
        return $arr;
    }

    //重新排序
    function getTree($arr,$pid=0,$level=0){
        static $list=array();
        foreach($arr as $value){
            if($value['pid']==$pid){
                $value['level']=$level+1;
                $list[]=$value;
                $this->getTree($arr,$value['id'],$level+1);
            }
        }
        return $list;
    }

基于TP5框架

得到如下结果:

array(5) {
  [0] => array(5) {
    ["id"] => int(1)
    ["pid"] => int(0)
    ["name"] => string(5) "lee01"
    ["mobile"] => string(0) ""
    ["level"] => int(1)
  }
  [1] => array(5) {
    ["id"] => int(2)
    ["pid"] => int(1)
    ["name"] => string(5) "lee02"
    ["mobile"] => string(0) ""
    ["level"] => int(2)
  }
  [2] => array(5) {
    ["id"] => int(3)
    ["pid"] => int(2)
    ["name"] => string(5) "lee03"
    ["mobile"] => string(0) ""
    ["level"] => int(3)
  }
  [3] => array(5) {
    ["id"] => int(5)
    ["pid"] => int(3)
    ["name"] => string(5) "lee05"
    ["mobile"] => string(0) ""
    ["level"] => int(4)
  }
  [4] => array(5) {
    ["id"] => int(4)
    ["pid"] => int(2)
    ["name"] => string(5) "lee04"
    ["mobile"] => string(0) ""
    ["level"] => int(3)
  }
}

 

你可能感兴趣的:(PHP,ThinkPHP)