views:

353

answers:

6

Hi guys,

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 block( $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>
A: 

how about

<pre>
<?php print_r($myArray); ?>
</pre>
Zak
A: 
function divArray($array){
    foreach($array as $key => $value){
       echo "<div>";
       echo $key;
       if(is_array($value)){
          divArray($value);
       }
       else{
         echo "$value";
      }
       echo "</div>";
  }
}
GSto
You're only closing the divs when is not an array.
Sergi
oops! You're right. corrected.
GSto
A: 
function block($a) {
    $ret = '<div>';
    if(is_array($a)) {
        foreach($a as $k => $v)
            $ret .= block($v); 
    } else {
        $ret .= $a;
    }
    $ret .= '</div>';
    return $ret;
}
Sergi
A: 
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);
Ben
oops Sergi beats me...
Ben
+3  A: 

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) {
    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>
Phil
The indentation is a nice touch.
notJim
You could change the firs iterator for str_repeat(' ',$depth)
Sergi
A: 

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