1

我正在使用递归函数在代码点火器中回显多级导航方案,它回显很好,但我想将该输出组合在一个变量中,并希望从调用函数的位置返回它,请帮助我这是我的代码


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

4

2 回答 2

3

试试这个:

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;
}
于 2012-08-01T08:12:45.570 回答
0

您只需使用 . 连接符(NB .=之间没有空格现在!)

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;
于 2012-08-01T08:12:56.730 回答