0

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"

4 Answers 4

3

php's foreach loop is what you need.

foreach($arr['keyId']['results'] as $key => $value) {
   //$key contains key and $value contains values.
}
Sign up to request clarification or add additional context in comments.

Comments

2

The array you want is $array['keyID']['results']. From there you access the values with $array['keyID']['results'][1], $array['keyID']['results'][2], $array['keyID']['results'][3]

To loop through it just do this:

foreach($array['keyId']['results'] as $key => $value) {
   echo $key . ' ' . $value;
}

or

for ($i = 1; $i <= 3; i++)
{
    echo $i . ' ' . $array['keyID']['results'][i];
}

Comments

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

Comments

1

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
       }
   }
}

14 Comments

What is wrong with SO, today? Downvotes are being fired on me. Without Comments.
@Jon, I meant SO users, I am afraid somebody hates me.
That's absurd. You should be more "afraid" that your answers need improvement: for example, this one is not practical at all and there is also no explanation at all. To me it looks like a bad idea and the OP may have difficult time adapting to other code on top of that.
@Jon, My answer has more explanation than yours does.
...which, along with the fact that we are talking about ultra beginner level PHP syntax, is why I made mine community wiki. It would have been a comment instead if I didn't need the space to format the code. In any case, it might serve you better to look into how your answers can be improved.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.