php递归树的实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wyljz/article/details/83112541

使用到了https://github.com/akanehara/ginq,这个类库可以在php中像.net一样使用linq

private function gettree(&$list, &$parent=null, &$tree=array())
    {
        $query = Ginq::from($list)->where(function ($m) use ($parent) {
            if (empty($parent)) {
                return  $m['parentId']==null;
            } else {
                return  $m['parentId']==$parent['id'];
            }
        })->toArray();
        
        foreach ($query as $row) {
            $node = array();
            $node['id']=$row['id'];
            $node['text']=$row['name'];
            $node['checked']=false;
            $node['children']=array();

            $v = Ginq::from($list)->count(function ($m) use ($row) {
                return $m['parentId']==$row['id'];
            });
            if ($v>0) {
                $this->gettree($list, $node, $tree);
            }

            if (!empty($parent)) {
                $parent['children'][]=$node;
            } else{
                $tree[]=$node;
            }
        }
        
        return $tree;
    }

这种实现一个是练习php的递归,另一个是学习linq的php用法,还有个简易的代码来实现递归树,同事给的,在我这里跑不起来

function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                        // $parent['children'][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }

猜你喜欢

转载自blog.csdn.net/wyljz/article/details/83112541