A recursive php function that turns a nested array into nested html blocks

I want to write a recursive php function that will call a function to generate nested HTML blocks (not necessarily just a DIV). 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 next function

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

will result in

 <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> 
+4
source share
6 answers

Sorry coarse formatting and a very coarse indentation method for you, but it should work the way you formatted above. Note 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> 
+7
source

What about

 <pre> <?php print_r($myArray); ?> </pre> 
+1
source
 function divArray($array){ foreach($array as $key => $value){ echo "<div>"; echo $key; if(is_array($value)){ divArray($value); } else{ echo "$value"; } echo "</div>"; } } 
0
source
 function block($a) { $ret = '<div>'; if(is_array($a)) { foreach($a as $k => $v) $ret .= block($v); } else { $ret .= $a; } $ret .= '</div>'; return $ret; } 
0
source
 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); 
0
source

Other answers did not take into account the fact that he wants to have the block() function as a 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
source

All Articles