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

  • 相关阅读:
    usaco-ariprog1-pass
    usaco-crypt1-pass
    usaco-barn-repair-pass-KISS
    usaco-mixing milk-pass
    面试HR
    LCS求最长公共子序列(DP)
    毕业随想(转载)
    0-1背包问题(DP)
    排序算法
    二叉搜索树的实现 java
  • 原文地址:https://www.cnblogs.com/wxjblog/p/6934543.html
Copyright © 2011-2022 走看看