将递归函数的输出组合到一个变量中


Combine output of recursive function in one variable

我在代码点火器中使用递归函数来回声多级导航方案echo很好,但我想把输出组合成一个变量,并从调用函数的地方返回请帮帮我,这是我的密码


    function parseAndPrintTree($root, $tree)
    {
        if(!is_null($tree) && count($tree) > 0) 
                {
                echo 'ul';
                foreach($tree as $child => $parent) 
                    {
                    if($parent->parent == $root) 
                        {
unset($tree[$child]); echo 'li'; echo $parent->name; parseAndPrintTree($parent->entity_id, $tree); echo 'li close'; } } echo 'ul close'; } }

Try this one:

function parseAndPrintTree($root, $tree)
{
    $output = '';
    if(!is_null($tree) && count($tree) > 0) 
        {
                $output .= 'ul';
                foreach($tree as $child => $parent) 
                    {
                    if($parent->parent == $root) 
                        {
                        unset($tree[$child]);
                        $output .=  'li';
                        $output .= $parent->name;
                        $output .= parseAndPrintTree($parent->entity_id, $tree);
                        $output .= 'li close';
                        }
                    }
                $output.= 'ul close';
    }
    return $output;
}

您只需使用。连接符符号(注意.=之间没有空格!)

function parseAndPrintTree($root, $tree)
{
    if(!is_null($tree) && count($tree) > 0) 
            {
            $data = 'ul';
            foreach($tree as $child => $parent) 
                {
                if($parent->parent == $root) 
                    {
                    unset($tree[$child]);
                    $data .= 'li';
                    $data .= $parent->name;
                    parseAndPrintTree($parent->entity_id, $tree);
                    $data .= 'li close';
                    }
                }
            $data .= 'ul close';
    }
return $data;
}
// then where you want your ul to appear ...
echo parseAndPrintTree($a, $b);

一个更好的名字可能是treeToUl()或类似的东西,更好地说明你对这个代码的意图(一个html无序列表?)

你也可以通过添加一些行尾来保持html输出的可读性,比如:

$data .= '</ul>' . PHP_EOL;