PHP通过关联数组迭代

时间:2013-03-07 23:46:23

标签: php associative-array

所以我有以下工作代码:

$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()提供的参数无效

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

编辑:哇,谢谢你的所有答案......不过,我会尽快接受最具体的答案。

3 个答案:

答案 0 :(得分: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)
   {
   }
}

答案 1 :(得分: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 

答案 2 :(得分:0)

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

仅使用$ value编码将数组(“Pear”,“Peach”,“Apple”,“Banana”)等数组放入$ value中,这不是数组的有效索引。