Reputation: 612
I need after the end of a loop in a recursive function to return the $build
variable
This is my code:
$traverse = function ($tree,$build = '') use (&$traverse) {
foreach ($tree as $key=>$menu) {
if (count($menu->children) > 0) {
$build .= "<li ><a href='" . $menu->url . "'>" . $menu->text . "</a><ul>";
$traverse( $menu->children,$build);
$build .= "</ul></li>";
} else {
$build .= "<li ><a href='" . $menu->url . "'>" . $menu->text . "</a></li>";
}
}
};
$traverse($tree );
Upvotes: 0
Views: 96
Reputation: 281
Regarding my comment u should have:
$traverse = function ($tree) use (&$traverse) {
$build = '';
if (count($menu->children) > 0) {
$build .= "<li ><a href='" . $menu->url . "'>" . $menu->text . "</a><ul>";
$build .= $traverse($menu->children);
$build .= "</ul></li>";
} else {
$build .= "<li ><a href='" . $menu->url . "'>" . $menu->text . "</a></li>";
}
return $build;
};
As u can see u also don't need to pass and use $build
as argument to the function.
Also u should check the html code for being valid at the end. Because of it won`t be.
Upvotes: 1