tahakirmani2 Posted May 30, 2013 Share Posted May 30, 2013 Hello, I am trying to fetch values from a Multidimensional array using foreach loop, i have understand the basics of foreach(){} loop, but when it comes to Multidimensional array i get confused. This is my program <?php $food =array( 'Healthy' => array('Salad','Rice', 'Vegetables'=>array('Tomatto','Onion')) , 'UnHealthy' => array('pasta', 'Vegetables'=>array('potatto', 'Corn')) ); I want to print all vegetables in my output, i have tried various way to do it, and search a lot of examples but fond nothing useful. Kindly tell me the way to do it. Thanks Quote Link to comment Share on other sites More sharing options...
Phear46 Posted May 30, 2013 Share Posted May 30, 2013 (edited) something like: foreach($food as $k => $v) { if(isarray($v)) { foreach($v as $key => $val) { echo $val; } } else { echo $v; } } That should work for an array like this $array = (key => val, key2 => val2, key3 => (val 3, val4, val5, val,6)) output : val val2 val3 val4 val5 val6if yours goes deeper youll have to add extra 'is array' tests. Thats how ive done it previously, probably not the best way but it works Edited May 30, 2013 by Phear46 Quote Link to comment Share on other sites More sharing options...
cpd Posted May 30, 2013 Share Posted May 30, 2013 I would consider using recursion to simplify your problem here as you have a 3 dimensional array. You need to consider how you want to display your data as well as this will affect the algorithm. Example function display(array $array) { $output = ""; foreach($array as $v) { $output.= (is_array($v) ? display($v) : $v); $output.= "<br />"; } return $output; } You can then use this function by doing $array = array(...); foreach($array as $v) { foreach($array as $v) { echo (is_array($v) ? display($v) : $v); echo "<br />"; } } That said, if you're unsure of the depth of your array you should consider a different data structure and definitely not use this method as it could cause overflow issues. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.