欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

无限极分类输出的方法

程序员文章站 2024-02-01 10:18:16
数据: $data = array( array( 'id' => 1, 'parent_id' => 0, 'name' => 'first' ), array( 'id' => 2, 'parent_id' => 1, 'name' => 'second' ), array( 'id' => 3 ......

数据:

$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;
}