Jump to content

foreach() loop for Multidimensional array


tahakirmani2

Recommended Posts

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

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/278586-foreach-loop-for-multidimensional-array/
Share on other sites

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 val6

if 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 :)

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.