September 11, 2012

array looping issue

Question by Nisanth

I have the following array

Array(
Array
(
    [Segment] => Array
        (
            [id] => 738
    )
),
Array
(
    [Segment] => Array
        (
            [0] => array([id] => 740),
            [1] => array([id] => 750)
    )
)
)

how can i loop the array. The second value need inner loop.

i need the output as

first loop as id->738

second loop as id->740, id->750

Regards,
Nisanth

Answer by Starx

You can do it like this:

foreach($array as $a) {
    foreach($a as $segment => $array) {
        if(isset($array['id'])) {
           echo $array['id']; //if there is an `id` index echo it
        } else {
           foreach($array as $k => $v) { //or else.. start looping again
               echo $v['id'];
           }
        }
    }
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!