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

Edited by Phear46
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.