Return content from function instead of echo

I have this recursive function:

    function displayTreeview($cats,$depth=0)
    {
        //if($depth==0){echo '<ul>';}
        foreach($cats as $cat)
        {
            $hasChildren=count($cat['children'])>0;
            $class = $hasChildren?' class="menu-item-has-children"':'';
            echo '<li'.$class.' data-children="'.count($cat['children']).'">'.$cat['name'];
            if($hasChildren){
             echo '<ul class="dropdown-menu sub-menu">';
             displayTreeview($cat['children'],$depth+1);echo '</ul>';}
             echo '</li>';
        }
        //if($depth==0){echo '</ul>';}
    }

How can I get all html code into a var and return it? I tried with $var .= to append but did not succeded to get the correct code.

Upvotes: 0

Views: 59

Answers (2)

ROAL
ROAL

Reputation: 1779

    function displayTreeview($cats,$depth=0, $stringBuilder)
    {
        $stringBuilder = '';
        //if($depth==0){echo '<ul>';}
        foreach($cats as $cat)
        {
            $hasChildren=count($cat['children'])>0;
            $class = $hasChildren?' class="menu-item-has-children"':'';
            $stringBuilder .= '<li'.$class.' data-children="'.count($cat['children']).'">'.$cat['name'];
            if($hasChildren){
                $stringBuilder .= '<ul class="dropdown-menu sub-menu">';
                $stringBuilder .= displayTreeview($cat['children'],$depth+1, $stringBuilder);
                $stringBuilder .= '</ul>';
            }
            $stringBuilder .= '</li>';
        }
        //if($depth==0){echo '</ul>';}

        return $stringBuilder;
    }

Notice the $stringBuilder = ''; at the begining (before the commented condition). You need to have this here, and then append to it in the cycle. The way you had it, the variable got reset on every run of the cycle.

Upvotes: 3

Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10967

Just replace every echo with a string append eg :

function displayTreeview($cats,$depth=0)
    {
        //if($depth==0){echo '<ul>';}
        $stringBuilder = "";
        foreach($cats as $cat)
        {
            $hasChildren=count($cat['children'])>0;
            $class = $hasChildren?' class="menu-item-has-children"':'';
            $stringBuilder .= '<li'.$class.' data-children="'.count($cat['children']).'">'.$cat['name'];
            if($hasChildren){$stringBuilder .='<ul class="dropdown-menu sub-menu">';displayTreeview($cat['children'],$depth+1);$stringBuilder .= '</ul>';}
            $stringBuilder .= '</li>';
        }
        //if($depth==0){echo '</ul>';}
        return $stringBuilder ;
    }

Upvotes: 1

Related Questions