Echo menu tree with recursive function

前端 未结 1 2034
南方客
南方客 2020-11-30 12:02

Problem: I can\'t think of way make a recursion function to my specific situation.

Situation:

Mysql DB
<

相关标签:
1条回答
  • 2020-11-30 12:40

    How about:

    function recurse($categories, $parent = null, $level = 0)
    {
        $ret = '<ul>';
        foreach($categories as $index => $category)
        {
            if($category['root'] == $parent)
            {
                $ret .= '<li><a href="#"><p class="Tier' . $level . '">' . $category['name'] . '</p></a>';
                $ret .= $this->recurse($categories, $category['id'], $level+1);
                $ret .= '</li>';
            }
        }
        return $ret . '</ul>';
    }
    

    This function requires that you first query your database for the entire list of available categories and assumes that your root categories have a value of null, but the function can be changed to accept -1 or 0 depending on how your current schema works.

    $categories = { get from database into an multi-dimensional array };
    $Tree = $this->recurse($categories);
    echo $Tree;
    

    You may consider doing the following to prevent any empty UL's appearing when no children exist for the parent:

    function recurse($categories, $parent = null, $level = 0)
    {
        $ret = '<ul>';
        foreach($categories as $index => $category)
        {
            if($category['root'] == $parent)
            {
                $ret .= '<li><a href="#"><p class="Tier' . $level . '">' . $category['name'] . '</p></a>';
                $sub = $this->recurse($categories, $category['id'], $level+1);
                if($sub != '<ul></ul>')
                    $ret .= $sub;
                $ret .= '</li>';
            }
        }
        return $ret . '</ul>';
    }
    

    However, the best solution, would be to select your data to include a column containing how many child categories each category has.

    select Category.*, (select count(distinct c1.id) from Category as c1 where c1.root = Category.id) as ChildCount from Category
    

    In which your function would be:

    function recurse($categories, $parent = null, $level = 0)
    {
        $ret = '<ul>';
        foreach($categories as $index => $category)
        {
            if($category['root'] == $parent)
            {
                $ret .= '<li><a href="#"><p class="Tier' . $level . '">' . $category['name'] . '</p></a>';
                if($category['ChildCount'] > 0)
                    $ret .= $this->recurse($categories, $category['id'], $level+1);
                $ret .= '</li>';
            }
        }
        return $ret . '</ul>';
    }
    

    Hope that helps?

    0 讨论(0)
提交回复
热议问题