Reputation:
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';
}
}
Upvotes: 1
Views: 602
Reputation: 6896
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;
Upvotes: 0
Reputation: 4250
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;
}
Upvotes: 3