Combine output of recursive function in one variable Combine output of recursive function in one variable codeigniter codeigniter

Combine output of recursive function in one variable


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


You just build up a string using the . concatenator symbol (NB no space between the . and = now!)

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

A better name might be treeToUl() or something similar, stating better what your intention is for this code ( a html unordered list?)

You can also keep your html output readable by adding some line ends like this:

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