April 17, 2012

how to reach into PHP nested arrays?

Question by user837208

I’ve a nested array whose print_r looks like this-

Array
(
    [keyId] => Array
        (
            [hostname] => 192.168.1.127
            [results] => Array
                (
                    [1] => false
                    [2] => false
                    [3] => false
                )

            [sessionIDs] => Array
                (
                    [0] => ed9f79e4-2640-4089-ba0e-79bec15cb25b
                )

        )

I would like to process(print key and value) of the “results” array. How do I do this?

I am trying to use array_keys function to first get all the keys and if key name is “results”, process the array. But problem is array_keys is not reaching into the “results”

Answer by Jon

foreach($array['keyId']['results'] as $k => $v) {
    // use $k and $v
}

Answer by Starx

One way to navigate through the array is this.

//Assuming, your main array is $array
foreach($array as $value) { //iterate over each item

   if(isset($value['results']) && count($value['results'])) { 
   // ^ check if results is present

       //Now that we know results exists, lets use foreach loop again to get the values
       foreach($value['result'] as $k => $v) {
           //The boolean values are now accessible with $v
       }
   }
}

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!