Php 无限极分类 递归查询 获取所有子类和父类

1、首先创建分类表 category


CREATE TABLE IF NOT EXISTS `category` (
  `categoryId` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `parentId` smallint(5) unsigned NOT NULL DEFAULT '0',
  `categoryName` varchar(50) NOT NULL,
  PRIMARY KEY (`categoryId`)

2、插入测试数据

CREATE TABLE IF NOT EXISTS `category` (
  `categoryId` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `parentId` smallint(5) unsigned NOT NULL DEFAULT '0',
  `categoryName` varchar(50) NOT NULL,
  PRIMARY KEY (`categoryId`)
)  ;
 
INSERT INTO `category` (`categoryId`, `parentId`, `categoryName`) VALUES
(1, 0, 'php'),
(2, 0, 'java'),
(3, 0, 'c/c++'),
(4, 1, 'php基础'),
(5, 1, 'php开源资料'),
(6, 1, 'php框架'),
(7, 2, 'java Se'),
(8, 2, 'java EE'),
(9, 2, 'java Me'),
(10, 3, 'c/c++基础编程'),
(11, 3, 'c/c++系统开发'),
(12, 3, 'c嵌入式编程'),
(13, 3, 'c++应用开发'),
(14, 13, 'c++桌面应用开发'),
(15, 13, 'c++游戏开发');

3、通过父级找子级

3.1、找某一个父级的直接子集


function getSons($categorys,$catId=0){
	$sons= [];
	foreach($categorys as $item){
		if($item['parentId']==$catId)
			$sons[]=$item;
	}
	return $sons;
}

 3.2、获取某个分类的所有子集

function getSubs($categorys,$catId=0,$level=1){
    $subs=array();
    foreach($categorys as $item){
        if($item['parentId']==$catId){
            $item['level']=$level;
            $subs[]=$item;
            $subs=array_merge($subs,getSubs($categorys,$item['categoryId'],$level+1));
            
        }
            
    }
    return $subs;
} 

4、通过子级找父级

4.1、获取某一个子类的所有父级  递归

   public function getParents($categorys,$parentId = '')
    {
        $tree = [];
        if($data){
            foreach ($categorysas $item){
                if($parentId != ''){
                    if($item['categoryId'] == $parentId){
                        $tree[] = $item;
                        $tree = array_merge($tree,$this->getAccordOe($data,$item['parentId']));
                    }
                }
            }

            return $tree;
        }
    }

4.2、获取某一个子类的所有父级  迭代

function getParents2($categorys,$catId){
	$tree=array();
	while($catId != 0){
		foreach($categorys as $item){
			if($item['categoryId']==$catId){
				$tree[]=$item;
				$catId=$item['parentId'];
				break;	
			}
		}
	}
	return $tree;
}

 

你可能感兴趣的:(层级查询,数据处理,数组)