从函数返回内容而不是echo

时间:2015-10-27 19:44:14

标签: php

我有这个递归函数:

    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>';}
    }

如何将所有html代码放入var并返回?我尝试使用$ var。=来追加,但没有成功获得正确的代码。

2 个答案:

答案 0 :(得分:3)

    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;
    }

注意开始时的$stringBuilder = '';(在评论条件之前)。你需要在这里有这个,然后在循环中追加它。按照你的方式,变量在循环的每次运行中都被重置。

答案 1 :(得分:1)

只需用字符串追加替换每个回声,例如:

.close_sesame {
 transform: rotatex(180deg);
 z-index: 9999 ;
}