zoukankan      html  css  js  c++  java
  • 无限极分类输出的方法

    数据:

    $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高级(2)—— 基础回顾2
    Java System Reports
    EWA不能及时通过邮件接收
    LA服务可用性4个9是什么意思?怎么达到?
    安装HANA Rules Framework(HRF)
    RFC destination fails with error Incomplete Logon Data after system copy
    为满足中国税改,SAP该如何打SPS
    HANA数据库无法停止
    SR开启时LOG_MODE必须是normal
    2743711
  • 原文地址:https://www.cnblogs.com/daxi-hu/p/8669561.html
Copyright © 2011-2022 走看看