Q:

build recursive tree with spaces

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?

A:

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);

