0

There is a tree $id => $children in array:

$tree = array(
    1 => array(
        2 => array(),
        3 => array(
            4 => array()
        )
    )
);

I need to echo this tree by id with spaces in front of each level:

1
    2
    3
        4

I use this function:

function build_tree($node)
{
    static $space = '';

    $space .= ' &nbsp &nbsp ';

    foreach ($node as $id => $children)
    {
        echo $space.$id.'<br />';
        build_tree($children);
    }
}

build_tree($tree);

But i couldn't handle spaces, they just added each iteration and result is:

1
    2
        3
            4

So, how can I make spaces to be the same for each level?

3
  • Why are you combining recursion and loops? Try to take out the loop and work your solution that way (if you're looking for elegance). In any case, it seems your spaces are based upon both parents and children - you will need to calculate the connection probably to know which level you are on and how many spaces you will need.
    – RageD
    Mar 5, 2011 at 18:33
  • How it can be used without loops?
    – Qiao
    Mar 5, 2011 at 18:34
  • The intent of recursion is to eliminate loops and nearly create an inductive proof that your algorithm works. So this can be done without loops, however, you would most likely need to use conditional statements. The solution which knittl pointed out below appears to me as it would be sufficient.
    – RageD
    Mar 5, 2011 at 18:39

2 Answers 2

2

You need to pass the level downward as you recurse:

function build_tree($node, $level=0) {
    static $space = ' &nbsp  &nbsp ';

    foreach ($node as $id => $children) {
        echo str_repeat($space, $level).$id.'<br />';
        if ($children) build_tree($children, $level+1);
    }
}

build_tree($tree);
1

you need to track the level you are currently in:

function build_tree($node, $level = 0)
{
    $space = str_repeat(' &nbsp &nbsp ', $level);

    foreach ($node as $id => $children)
    {
        echo $space.$id.'<br />';
        if(is_array($children))
          build_tree($children, $level+1);
    }
}

build_tree($tree, 0);
1
  • LOL... you beat me by 30 seconds. You have a typo - $levl Mar 5, 2011 at 18:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.