zoukankan      html  css  js  c++  java
  • PHP实现无限级分类

    前段时间做一个小项目的时候用到了无限级分类,当时也忘的差不多了,于是就去网上查资料学,下面是我的学习笔记

    数据格式:

    array (size=5)
      1 => 
        array (size=6)
          'id' => string '1' (length=1)
          'pid' => string '0' (length=1)
          'name' => string '青年之声1' (length=13)
          'description' => string '' (length=0)
          'create_time' => string '2017-04-02 15:38:06' (length=19)
          'del' => string '0' (length=1)
      2 => 
        array (size=6)
          'id' => string '2' (length=1)
          'pid' => string '1' (length=1)
          'name' => string '青年之声2' (length=13)
          'description' => string '' (length=0)
          'create_time' => string '2017-04-02 15:38:06' (length=19)
          'del' => string '0' (length=1)
      3 => 
        array (size=6)
          'id' => string '3' (length=1)
          'pid' => string '2' (length=1)
          'name' => string '青年之声3' (length=13)
          'description' => string '' (length=0)
          'create_time' => string '2017-04-02 15:38:06' (length=19)
          'del' => string '0' (length=1)
      4 => 
        array (size=6)
          'id' => string '4' (length=1)
          'pid' => string '3' (length=1)
          'name' => string '青年之声4' (length=13)
          'description' => string '' (length=0)
          'create_time' => string '2017-04-02 15:38:06' (length=19)
          'del' => string '0' (length=1)
      5 => 
        array (size=6)
          'id' => string '5' (length=1)
          'pid' => string '4' (length=1)
          'name' => string '青年之声5' (length=13)
          'description' => string '' (length=0)
          'create_time' => string '2017-04-02 15:38:06' (length=19)
          'del' => string '0' (length=1)
    

    非递归算法

    $tree = array();
    foreach ($items as $item) {
    	if (isset($items[$item['pid']])) {
    		$items[$item['pid']]['childs'][] = &$items[$item['id']];
    	} else {
    		$tree[] = &$items[$item['id']];
    	}
    }
    

    递归算法

    function getChild($id) {
    	$tree = [];
    	$childs = Columns::find()->where(['pid' => $id, 'del' => 0])->asArray()->all();
    	if ($childs) {
    		foreach ($childs as $child) {
    			$childTree = getChild($child['id']);
    			if ($childTree) {
    				$child['children'] = $childTree;
    			}
    			$tree[] = $child;
    		}
    	}
    	return $tree;
    }
    

    最终结果

    Paste_Image.png

  • 相关阅读:
    Linux常用命令
    ServerSocketChannel和SocketChannel
    Java扫描包
    [BZOJ3874/AHOI2014]宅男计划
    [BZOJ4029/HEOI2015]定价
    [考试]20151012贪心
    [BZOJ4027/HEOI2015]兔子与樱花
    [考试]20151010
    [考试]20151009
    Test of String
  • 原文地址:https://www.cnblogs.com/wxjblog/p/6934543.html
Copyright © 2011-2022 走看看