无限极分类输出的方法
数据:
$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;
}
上一篇: Oracle的集合运算符