| Recursive foreach()
|
Readie

msg:4143673 | 7:46 pm on May 29, 2010 (gmt 0) | I had reason to need a recursive foreach function that was similar to array_walk_recursive - but I actually needed the key name of the lower leveled arrays as well. So, stripped down a little bit, but preserving the key functionality: [pre]function recursive_foreach($array) { $out = ''; foreach($array as $key => $value) { $out .= '<br>' . $key; if(!is_array($value)) { $out .= ' - ' . $value; } else { $out .= recursive_foreach($value); } } return $out; }[/pre] |
| Test: [pre]$the_array = array( 0 => array( 0 => 'a', 1 => 'b', 'c' => 3, 'd' => array( 3 => 2, 'a' => 'b', 'c' => 2 ) ), 1 => array( 'e', 'f' => 'g', 'h' => 2, 65 => 35, 32 => 'i' ), 'foo' => array( 'j', 'k' => 'l' ), 'bar' );
echo recursive_foreach($the_array);[/pre] |
| Output: 0 0 - a 1 - b c - 3 d 3 - 2 a - b c - 2 1 0 - e f - g h - 2 65 - 35 32 - i foo 0 - j k - l 2 - bar |
| Just thought I'd share incase anyone finds themselves needing something similar :)
|
|