1

所以我有以下工作代码:

$arrayitertest=Array("Fruit"=>Array("Pear","Peach","Apple","Banana"),"Cars"=>Array("My budget","other cars."));

foreach ($arrayitertest as $key=>$value)
foreach($arrayitertest[$key] as $result) echo $key.":". $result."|";

但是当我改变它foreach ($arrayitertest as $key => $value)foreach ($arrayitertest as $key)会引发一个致命错误(尽管我从未使用过 $key 变量。)

错误是:为 foreach() 提供的参数无效

有人可以告诉我为什么会这样吗?

编辑:哇,感谢所有答案....不过,我会接受目前最具体的答案。

4

3 回答 3

4

就您的错误而言:如果您$value从第一个中删除foreach,$key将成为值并$arrayitertest[$key]成为"pear"第二个的无效参数foreach

您的程序将在以下时间停止:

// this is not going to work
foreach ("pear" as $result)

如果您不需要第一个密钥,则foreach可以将其更改为:

foreach ($arrayitertest as $value)
{
   foreach($value as $result)
   {
   }
}
于 2013-03-07T23:53:51.380 回答
3

我认为您误解了键和值的顺序。你说$value => $key的是技术上的$key => $value

解析数组的方法是这样的:

foreach ($array as $key => $value) {
    foreach ($array[$key] as $v) {
        // $v = Pear (1st iteration), Peach (2nd), Apple (3rd) ... (for key = Fruit) 
        // $v = My Budget (1st iteration), other cars. (2nd) (for key = Cars)
        // notice that $key is also accessible here
    }
}

显然,如果您不需要,$key您可以简单地:

foreach ($array as $a)
    foreach ($a as $v)
        // use $v here 
于 2013-03-07T23:52:59.900 回答
0

编码 $value => $key, 将 Fruit, Car, ... 放入 $value。

仅编码 $value 会将诸如 Array("Pear","Peach","Apple","Banana") 之类的数组放入 $value 中,这不是数组的有效索引。

于 2013-03-07T23:55:12.950 回答