PHP : Foreach function for multi level array’s
Valerie Joy posted an article about Array’s on her blog. She handles the basics of array construction and how to translate the array to string with the php build-in foreach function.
Now it would be nice to show you how to handle multi-level array’s and how you can construct an function to translate these array’s to string.
First of all we need to have an array with multiple array’s inside.
$my_array = array('visitors'=>array(
'members'=>array(
'member1'=>'jim',
'member2'=>'john'),
'visitors'=>array(
'visitor1'=>'127.0.0.1',
'visitor2'=>'196.68.0.1')
)
);
Now we the array we can construct an function to handle this array.
$buff = "";
function foreach_loop(&$array) {
global $buff;
foreach ($array as $key => $value ) {
if (!is_array($value)) { // if it isn't an array show $key and $value
$buff .= ' ' . $key;
$buff .= ' -> ' . $value;
}else { // if it is an array -> show $key -> then process $value again will same function.
$buff .= '‘ . $key.’‘;
foreach_loop($value);
}
}
}
Now, just before the function i’ve defined a variable called “$buff”, this value is going to hold the complete autput generated by the function. To show it we first run the function and just after that we can echo or print it.
foreach_loop($my_array); echo $buff;
I think the function speaks for it self, first step of the function is to split the array up in $key and $value , then we check if the value relative to the $key is an array, if this isn’t the case we can append the $key and $value to our buffer $buff for later output, if however $value is an array we run the same function on this specific $value, and the who process starts over again.
I hope this piece of code is useful to you . please leave a comment.
Tags: array, foreach, multi level array, php
























March 14th, 2008 at 12:35 am
phew! that is really complicated!!
i wonder how that would look like..
val’s last blog post..Oh javascript!
March 14th, 2008 at 12:38 am
if there is anything you would like to have explained let me know
October 22nd, 2009 at 9:04 am
nice tutorial
May 1st, 2010 at 9:43 pm
Thank you for codes.
August 24th, 2011 at 6:22 am
Good – I should certainly pronounce, impressed with your site. I had no trouble navigating through all tabs as well as related info ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your client to communicate. Excellent task.
December 11th, 2011 at 11:47 am
must look at this to take huge discount for more detail