0

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

Edited by pritaeas: Moved.

4
Contributors
3
Replies
41
Views
4 Years
Discussion Span
Last Post by diafol
1

You can use a recursive function which checks if the value of the pair $key => $value is an array, in this case it loops again, an example:

<?php

    $food = array(
        'Healthy'   => array('Salad','Rice','Vegtables' => array('Tomatto','Onion')),
        'UnHealthy' => array('pasta', 'Vegetables' =>array('potatto', 'Corn')));

    function recursive_loop($array)
    {
        foreach($array as $key => $value)
        {
            if(is_array($value))
            {
                recursive_loop($value);
            }
            else
            {
                echo $value . PHP_EOL;
            }
        }
    }

    echo recursive_loop($food);
0

I am totally aggree with function made by @cereal. You can use that.

In addiotion to that function you can check $key. If key equal to "Vegetables" you can display value of "Vegetables"

1

You could probably do the external call without the preceeding echo. SO this should work:

recursive_loop($food);
Votes + Comments
Thanks! I didn't even thought about that!
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.