开发者

Recursive php function that turns nested array into nested html blocks

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'
);

and the following function

function blo开发者_StackOverflow社区ck( $key ) {
    return '<div>'.$key.'</div>';
}

would result into

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


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

CODE

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

OUTPUT

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


how about

<pre>
<?php print_r($myArray); ?>
</pre>


function block($a) {
    $ret = '<div>';
    if(is_array($a)) {
        foreach($a as $k => $v)
            $ret .= block($v); 
    } else {
        $ret .= $a;
    }
    $ret .= '</div>';
    return $ret;
}   


function block($array)
{
    $s = '';
    foreach ($array as $key=>$value)
    {
        $s .= '<div>' . $key ;
        if (is_array($value))
            $s .= block($value);
        else
            $s .= $value;
        $s .= '</div>';
    }
    return $s;
}
echo block($a);


function divArray($array){
    foreach($array as $key => $value){
       echo "<div>";
       echo $key;
       if(is_array($value)){
          divArray($value);
       }
       else{
         echo "$value";
      }
       echo "</div>";
  }
}


The other answers did not take into account the fact that he wants to be able to give the block() function as parameter :

function toNested($array, $blocFunc) {
    $result = '';

    foreach ($array as $key => $value) {
        if is_array($value)
            $nestedElement = toNested($value, $blocFunc);
        else
            $nestedElement = $blocFunc($key)

        $result .= $nestedElement;
    }

    return $result;
}

echo toNested($a, 'block');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜