递归php函数,可将嵌套数组转换为嵌套html块 [英] Recursive php function that turns nested array into nested html blocks

查看:63
本文介绍了递归php函数,可将嵌套数组转换为嵌套html块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找编写一个递归php函数,该函数将调用一个函数来生成嵌套的HTML块(不一定只是DIV).因此,例如,对于以下数组:

I'm looking to write a recursive php function that would call a function to generate nested HTML blocks ( not necessarily only DIVs ). So for example, for the following array:

$a = array(
    'b' => 'b value',
    'c' => 'c value',
    'd' => array(
        'd1' => array(
            'd12' = 'd12 value'
        ),
        'd2' => 'd2 value'
    ),
    'e' => 'e value'
);

以及以下功能

function block( $key ) {
    return '<div>'.$key.'</div>';
}

会导致

<div>
    key - b
</div>
<div>
    key - c
</div>
<div>
    key - d
    <div>
        key - d1
        <div>
            key - d12
        </div>
    </div>
    <div>
        key - d2
    </div>
</div>
<div>
    key - e
</div>

推荐答案

请原谅粗略的格式和缩进的粗略方式,但是它应该与上面的格式一样工作.注意使用in_array(...)

Excuse the crude formatting and the very crude way of indenting for you, but it should work as you've formatted above. Notice the use of in_array(...)

代码

nestdiv($a);

function nestdiv($array, $depth = 0) {
    $indent_str = str_repeat(" ", $depth);

    foreach ($array as $key => $val) {
        print "$indent_str<div>\n";
        print "${indent_str}key - $key\n";
        if (is_array($val))
            nestdiv($val, ($depth+1));
        print "$indent_str</div>\n";
    }
}

输出

<div>
key - b
</div>
<div>
key - c
</div>
<div>
key - d
    <div>
    key - d1
        <div>
        key - d12
        </div>
    </div>
    <div>
    key - d2
    </div>
</div>
<div>
key - e
</div>

这篇关于递归php函数,可将嵌套数组转换为嵌套html块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆