PHP: Formatting multi-dimensional array as HTML?

Posted by Industrial on Stack Overflow See other posts from Stack Overflow or by Industrial
Published on 2010-06-08T13:10:48Z Indexed on 2010/06/08 13:12 UTC
Read the original article Hit count: 195

Filed under:
|
|
|
|

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!

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays