PHP: Formatting multi-dimensional array as HTML?

久未见 提交于 2020-01-15 12:09:34

问题


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:


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


来源:https://stackoverflow.com/questions/2997548/php-formatting-multi-dimensional-array-as-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!