1

i am using recursive function to echo multi-level navigation scheme in code-igniter it echo's fine but i want to combine that output in one varible and want to return it from where the function is called please, help me here is my code


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

2
  • @JanHančič Accepted dear Earlier i don't know how o accept i tried to vote up but i says u have reputation below 15 Commented Aug 1, 2012 at 7:44
  • Click the green checkmark next to answer you want to accept. Commented Aug 1, 2012 at 7:47

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;

1 Comment

dear Shayan Husaini below is right because, in ur case it only prints parent ul's not their childs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.