0

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 );
6
  • 1
    Just add return $build; before the closing } of the function? Commented Oct 6, 2018 at 12:36
  • this way return just first loop and stop Commented Oct 6, 2018 at 12:37
  • It would be easier to debug if you could supply some sample input data and expected output... Commented Oct 6, 2018 at 12:39
  • this is nested set array , and each array have self children Commented Oct 6, 2018 at 12:41
  • 1
    Nick was correct: u should add return $build; before the closing } of the function. But also u should concat returned value inside the function - need to change $traverse( $menu->children,$build); to $build .= $traverse( $menu->children,$build); Commented Oct 6, 2018 at 13:29

1 Answer 1

1
+50

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.