views:

44

answers:

1

Hi everybody,

I have tried to get my head around building a recursive function to handle formatting of a unknown depth multi-dimensional array to HTML and nested Divs. I thought that it should be a piece of cake, but no.

Here's what I have come up with this far:

function formatHtml($array) {
    $var = '<div>';

    foreach ($array as $k => $v) {

            if (is_array($v['children']) && !empty($v['children'])) {
                formatHtml($v['children']);
            }
            else {
                $var .= $v['cid'];
            }
    }

    $var.= '</div>';

    return $var;
}

And here's my array:

Array
(
    [1] => Array
        (
            [cid] => 1
            [_parent] => 
            [id] => 1
            [name] => 'Root category'
            [children] => Array
                (
                    [2] => Array
                        (
                            [cid] => 2
                            [_parent] => 1
                            [id] => 3
                            [name] => 'Child category'   
                            [children] => Array ()
                        )
                )
        )
)

Thanks a lot!

+2  A: 

You're missing only one important piece: when you make the recursive call to formatHtml() you're not actually including the returned content anywhere! Append it to $var and you should get much better results:

function formatHtml($array) {
    $var = '<div>';

    foreach ($array as $k => $v) {

            if (is_array($v['children']) && !empty($v['children'])) {
                $var .= formatHtml($v['children']);
            }
            else {
                $var .= $v['cid'];
            }
    }

    $var.= '</div>';

    return $var;
}
VoteyDisciple