PHP无限级分类

function generateTree($items){
    $tree = array();
    foreach($items as $item){
        if(isset($items[$item['pid']])){
            $items[$item['pid']]['son'][] = &$items[$item['id']];
        }else{
            $tree[] = &$items[$item['id']];
        }
    }
    return $tree;
}
$items = array(
    1 => array('id' => 1, 'pid' => 0, 'name' => '安徽省'),
    2 => array('id' => 2, 'pid' => 0, 'name' => '浙江省'),
    3 => array('id' => 3, 'pid' => 1, 'name' => '合肥市'),
    4 => array('id' => 4, 'pid' => 3, 'name' => '长丰县'),
    5 => array('id' => 5, 'pid' => 1, 'name' => '安庆市'),
);
print_r(generateTree($items));


输出结果

Array
(
    [0] => Array
        (
            [id] => 1
            [pid] => 0
            [name] => 安徽省
            [son] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [pid] => 1
                            [name] => 合肥市
                            [son] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 4
                                            [pid] => 3
                                            [name] => 长丰县
                                        )
  
                                )
  
                        )
  
                    [1] => Array
                        (
                            [id] => 5
                            [pid] => 1
                            [name] => 安庆市
                        )
  
                )
  
        )
  
    [1] => Array
        (
            [id] => 2
            [pid] => 0
            [name] => 浙江省
        )
 
)

上面生成树方法还可以精简到5行:

function generateTree($items){
    foreach($items as $item)
        $items[$item['pid']]['son'][$item['id']] = &$items[$item['id']];
    return isset($items[0]['son']) ? $items[0]['son'] : array();
}

/**
 * 如何取数据格式化的树形数据
 */
$tree = generateTree($items);
function getTreeData($tree){
    foreach($tree as $t){
        echo $t['name'].'<br>';
        if(isset($t['son'])){
            getTreeData($t['son']);
        }
    }
}
getTreeData($tree);

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++游戏开发');


*/

//获取某分类的直接子分类
function getSons($categorys,$catId=0){
	$sons=array();
	foreach($categorys as $item){
		if($item['parentId']==$catId)
			$sons[]=$item;
	}
	return $sons;
}

//获取某个分类的所有子分类
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;
}

//获取某个分类的所有父分类
//方法一,递归
function getParents($categorys,$catId){
	$tree=array();
	foreach($categorys as $item){
		if($item['categoryId']==$catId){
			if($item['parentId']>0)
				$tree=array_merge($tree,getParents($categorys,$item['parentId']));
			$tree[]=$item;	
			break;	
		}
	}
	return $tree;
}

//方法二,迭代
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;
}


//测试 部分
$pdo=new PDO('mysql:host=localhost;dbname=test','root','8888');
$stmt=$pdo->query("select * from category order by categoryId");
$categorys=$stmt->fetchAll(PDO::FETCH_ASSOC);

$result=getSons($categorys,1);
foreach($result as $item)
	echo $item['categoryName'].'<br>';
echo '<hr>';

$result=getSubs($categorys,0);
foreach($result as $item)
	echo str_repeat('  ',$item['level']).$item['categoryName'].'<br>';
echo '<hr>';

$result=getParents($categorys,7);
foreach($result as $item)
	echo $item['categoryName'].' >> ';
echo '<hr>';

$result=getParents2($categorys,15);
foreach($result as $item)
	echo $item['categoryName'].' >> ';






?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值