树结构:验证树的深度级别

时间:2014-03-31 18:53:22

标签: javascript php tree fancytree

我使用fancytree构建了类别树。从root开始的每个节点的深度必须等于4,所以我可能有:

  • 类别
    • 子类别1
      • 子类别2
        • subcategory 4
      • 子类别5
        • 子类别6

脚本应该只允许保存到数据库那种结构。我试图在Fancytree API中找到一些与深度相关的方法,但我找不到合适的方法。

我决定编写后端验证,我有类似的东西:

        private function validateTree($tree)
        {
            foreach($tree as $node)
            {
                $parentName = $node['title'];
                if(isset($node['children']) and is_array($node['children']))
                {
                    if($this->validateLevel($node['children']) < 4)
                    {
                        $this->errors[] = $parentName;
                    }
                }
                else
                {
                    $this->errors[] = $parentName;
                }
            }
        }

        private function validateLevel($nodes, &$depth = 2)
        {
            foreach($nodes as $node)
            {
                if(isset($node['children']) and !empty($node['children']) and is_array($node['children']))
                {
                    $this->validateLevel($node['children'], ++$depth);
                }
                else
                {
                    return $depth;
                }
            }

        }

这不会按预期工作,可能无法验证每个根节点的每个子节点。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

看起来没有人可以帮助我(除了指出拼写错误),所以我自己想出来了。 这有点丑陋的解决方案,但它的工作方式与我想要的一样:

private function validateTree($tree)
    {
        foreach($tree as $node)
        {
            $parentName = $node['title'];
            if(isset($node['children']) and is_array($node['children']))
            {
                if((bool)$node = $this->validateLevel($node['children']))
                {
                    $this->errors[] = $node;
                }
            }
            else
            {
                $this->errors[] = $node;
            }
        }
    }

    private function validateLevel($nodes)
    {
        foreach($nodes as $node)
        {
            if(isset($node['children']) and (bool)$node['children'] and is_array($node['children']))
            {
                foreach($node['children'] as $nodeLvl3)
                {
                    if(isset($nodeLvl3['children']) and (bool)$nodeLvl3['children'] and is_array($nodeLvl3['children']))
                    {
                        foreach($nodeLvl3['children'] as $nodeLbl)
                        {
                            //everything is OK
                        }
                    }
                    else
                    {
                        $this->errors[] = 'Category'.$nodeLvl3['title'].' does not have lvl 4';
                    }
                }
            }
            else
            {
                $this->errors[] = 'Category'.$node['title'].' does not have lvl 3';
            }
        }
    }