我可以使用 foreach 迭代两个大小相等的循环吗?
我是 PHP 新手。我有两个大小相等的数组 $array1
和 $array2
。我一直在使用 foreach
循环来迭代数组,如下所示:
foreach($array1 as $element1) {
//Do stuff with $element1
}
但
foreach($array2 as $element2) {
//Do stuff with $element2
}
现在我想同时迭代两个数组,以便我可以访问两个 $element1< /code> 和
$element2
在循环体中。
我该怎么做?
I'm new to PHP. I have two arrays $array1
and $array2
of equal size. I've been using foreach
loops to iterate through arrays like so:
foreach($array1 as $element1) {
//Do stuff with $element1
}
and
foreach($array2 as $element2) {
//Do stuff with $element2
}
but now I'd like to iterate through both arrays at the same time so that I have access to both $element1
and $element2
in the loop body.
How do I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
但如果
false
是$array1
中允许的值,它将失败。如果(在这种情况下)$array2
中不允许false
,则可以交换两个“foreach”解决方案(如果两者共享相同的密钥)
第三个(我认为相当不错)的解决方案,只允许
$array1
中的原始类型But it will fail, if
false
is an allowed value in$array1
. If (in this case)false
is not allowed in$array2
, you can just swap bothA "foreach"-solution (if both shares the same key)
A third (I think quite nice) solution, that just allows primitive types in
$array1
Each 返回一个包含键和值的数组,并将指针前进到下一个元素。一旦超过最后一个元素,它就会返回 false。
要完全迭代两个数组,请使用 ||而不是 &&。
Each returns an array containing the key and value, and advances the pointer to the next element. It returns false once it has advanced past the last element.
To iterate completely over both arrays, use || instead of &&.
使用 for 循环代替...
如果数组的索引是数字并且两个数组都相同,则这将起作用
use a for loop instead...
This will work if the indexes of the arrays are numeric and the same for both arrays
你显然
想将 $stuff_this_array 和 $stuff_from_other_array 放入更持久的东西中,但这也许给你一个想法。
What about
You'd obviously want to put $stuff_this_array and $stuff_from_other_array into something more persistent, but maybe this gives you an idea.
这是一个可能的解决方案。如果直接从 next() 开始,则永远不会获得数组的第一个元素。
That is a possible solution. If you start with next() directly, you never get the first element of the array.