我可以通过foreach循环两个大小相等的循环吗? [英] Can I iterate through two loops of equal size with foreach?

查看:383
本文介绍了我可以通过foreach循环两个大小相等的循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP的新手。我有两个相同大小的数组 $ array1 $ array2 。我一直在使用 foreach 循环遍历数组,如下所示:

  foreach($ array1 as $ element1){
//用$ element1
做的东西}

  foreach($ array2 as $ element2){
//用$ element2做东西



$ b $ p
$ b

现在我想同时遍历两个数组我可以在循环体中访问 $ element1 $ element2



我该怎么做?

解决方案

  while( $ element1 = next($ array1))!== false){
$ element2 = next($ array2);
//做某事
}

但如果<$ code> false $ array1 中的允许值。如果(在这种情况下) false 在 $ array2 中是不允许的,那么您可以交换两个



foreach - 解决方案(如果两个共享同一个键)

  foreach $ array1 as $ i => $ element1){
$ element2 = $ array2 [$ i];
//做点什么
}

第三个(我觉得挺好的)解决方案,只是允许原始类型 $ array1

  foreach(array_combine ($ array $ value1),array_values($ array2))$ element1 p $ p> 

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?

解决方案

while (($element1 = next($array1)) !== false) {
  $element2 = next($array2);
  // Do something
}

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 both

A "foreach"-solution (if both shares the same key)

foreach ($array1 as $i => $element1) {
  $element2 = $array2[$i];
  // Do something
}

A third (I think quite nice) solution, that just allows primitive types in $array1

foreach (array_combine(array_values($array1), array_values($array2)) as $element1 => $element2) {
  // Do something
}

这篇关于我可以通过foreach循环两个大小相等的循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆