• 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

  • 相关阅读:
    mac上finalShell的安装
    c 字符串与字符串操作
    .net5 MailKit
    c 99乘法表
    element 动态表单加自定义校验
    遇到的问题 vscode 问题
    vue-element-admin eslint 规则查询表
    利用html2canvas 导出网页 (只是用于自己的笔记,如果需要看配置,自行查找插件api)
    git 常用命令
    uniapp中自动打包微信小程序后自动上传代码
  • 原文地址:https://www.cnblogs.com/jeferwang/p/6934543.html
Copyright © 2020-2023  润新知