0

我有一个嵌套数组,它的 print_r 看起来像这样-

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

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

        )

我想处理(打印键和值)“结果”数组。我该怎么做呢?

我正在尝试使用 array_keys 函数首先获取所有键,如果键名是“结果”,则处理数组。但问题是 array_keys 没有进入“结果”

4

4 回答 4

3

php 的foreach循环就是您所需要的。

foreach($arr['keyId']['results'] as $key => $value) {
   //$key contains key and $value contains values.
}
于 2012-04-17T11:00:18.703 回答
2

你想要的数组是$array['keyID']['results']. 从那里您可以使用$array['keyID']['results'][1], $array['keyID']['results'][2],访问值$array['keyID']['results'][3]

要遍历它,只需执行以下操作:

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

或者

for ($i = 1; $i <= 3; i++)
{
    echo $i . ' ' . $array['keyID']['results'][i];
}
于 2012-04-17T11:01:33.330 回答
1
foreach($array['keyId']['results'] as $k => $v) {
    // use $k and $v
}
于 2012-04-17T10:58:30.070 回答
1

浏览数组的一种方法是这样。

//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
       }
   }
}
于 2012-04-17T10:59:17.310 回答