• 无限极分类输出的方法


    数据:

    $data = array(
      array(
        'id' => 1,
        'parent_id' => 0,
        'name' => 'first'
      ),
      array(
        'id' => 2,
        'parent_id' => 1,
        'name' => 'second'
      ),
      array(
        'id' => 3,
        'parent_id' => 2,
        'name' => 'third'
      ),
      array(
        'id' => 4,
        'parent_id' => 3,
        'name' => 'forth'
      ),
    );

    调用:$res = $this->make_tree1($data);

    封装方法

    方法一:foreach循环

      

    //方法一:foreach循环实现无限极
    public function make_tree($list,$pk='id',$pid='parent_id',$child='children',$root=0)
    {
      $tree = array();
      $temp = array();
      foreach ($list as $data)
      {
        $temp[$data[$pk]] = $data;
      }
      foreach ($temp as $key =>$val)
      {
        if($val[$pid]==$root)
        { //代表跟节点
          $tree[]=& $temp[$key];
        }
        else
        {
        //找到其父类
        $temp[$val[$pid]][$child][]=& $temp[$key];
        }
      }
      return $tree;
    }

    //方法二:递归方法实现无限极
    public function make_tree1($list,$pk='id',$pid='parent_id',$child='children',$root=0)
    {
      $tree = array();
      foreach($list as $key=> $val)
      {
        if($val[$pid]==$root)
        {
          //获取当前$pid所有子类
          unset($list[$key]);
          if(!empty($list))
          {
            $child = $this->make_tree1($list,$pk,$pid,$child,$val[$pk]);
            if(!empty($child))
            {
              $val['_child'] = $child;
            }
          }
          $tree[]=$val;
        }
      }
      return $tree;
    }

  • 相关阅读:
    (转+原)python中的浅拷贝和深拷贝
    (原)torch7中添加新的层
    (原+转)ubuntu终端输出彩色文字
    (原)torch中显示nn.Sequential()网络的详细情况
    (原)python中使用plt.show()时显示图像
    eclipse 注释模板
    leetcode 11 最大盛水容器
    leetcode 9 回文数字
    leetcode8 字符串转整数
    利用Intent启动activity的例子
  • 原文地址:https://www.cnblogs.com/daxi-hu/p/8669561.html
Copyright © 2020-2023  润新知