1

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

1 Answer 1

2

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;
}
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.