一个不错的对分类进行树形结构返回的函数,有时候需要这种函数不好找(找了很多都不好用),自己写又有点花时间,所以经常记录一下比较好:
//通用返回父类和子类分类树,树形,php tree //getTree($data,'category_id','parent_id'); function getTree($arr, $id = 'id', $fid = 'fid', $child_name = 'children') { $refer = array(); $tree = array(); foreach ($arr as $k => $v) { $refer[$v[$id]] = &$arr[$k]; //创建主键的数组引用 } foreach ($arr as $k => $v) { $pid = $v[$fid]; //获取当前分类的父级id if ($pid == 0) { $tree[] = &$arr[$k]; //顶级栏目 } else { if (isset($refer[$pid])) { $refer[$pid][$child_name][] = &$arr[$k]; //如果存在父级栏目,则添加进父级栏目的子栏目数组中 } } } return $tree; }
举个栗子:
$arr = [ ['name'=>'a','pid'=>0,'id'=>1], ['name'=>'b','pid'=>1,'id'=>2], ['name'=>'d','pid'=>2,'id'=>4], ['name'=>'g','pid'=>1,'id'=>7], ['name'=>'gg','pid'=>8,'id'=>8], ['name'=>'gggg','pid'=>0,'id'=>10], ['name'=>'ggggg','pid'=>7,'id'=>11], ['name'=>'g2','pid'=>11,'id'=>12], ]; print_r(json_encode(getTree($arr,'id','pid','children')));
结果: