简体   繁体   English

在foreach中放一个foreach

[英]putting a foreach inside foreach

I'm trying to loop some array using foreach . 我试图使用foreach循环一些数组。 This is the code which demonstrates what I'm doing: 这是演示我在做什么的代码:

 $arr1=array("32,45,67,89");
    $arr2=array("5,3,2,1");

    foreach($arr1 as $key => $val){
      foreach($arr2 as $key2 =>$val2){
         echo $val."-".$key2."-".$val2;
        }
}

However, this outputs 但是,此输出

32-0-5 32-0-5

32-1-3 32-1-3

32-2-2 32-2-2

32-3-1 32-3-1

and I want to display it like this instead 我想这样显示它

32-1-5 32-1-5

45-2-3 45-2-3

67-3-2 67-3-2

89-3-1 89-3-1

How can I solve this? 我该如何解决? Since I'm a beginner I don't know what to do. 由于我是初学者,所以我不知道该怎么办。

You don't want to loop over the 2nd array, you just want to get the value at a certain position. 您不想在第二个数组上循环,只想在某个位置获取值。 Try it like this: 像这样尝试:

foreach($arr1 as $key => $val){
  $val2 = $arr2[$key];
  echo $val."-".($key+1)."-".$val2;
}

I assume you're doing a double foreach because you actually want to print 4*4 = 16 rows. 我假设您正在执行两次foreach,因为您实际上要打印4 * 4 = 16行。 I also assume that you mistyped the last row, where you have a 3 instead of a 4. 我还假设您输错了最后一行,您输入的是3而不是4。

Just using ($key2+1) can be enough for you ? 仅使用($ key2 + 1)就足够了吗?

$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");

foreach($arr1 as $key => $val){
  foreach($arr2 as $key2 =>$val2){
     echo $val."-" . ($key2+1) . "-".$val2;
  }
}

$i<count ($arr1) counts the number of elements in the array. $i<count ($arr1)计算数组中元素的数量。 And then stop once it gets to the end. 一旦结束,就停止。

If you have the name number of elements in each array. 如果您知道每个数组中元素的名称。 This would be great for you or even to create tables dynamically. 这对您甚至是动态创建表都非常有用。

$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");

for ($i=0; $i<count ($arr1) ; $i++){
echo $arr1[$i] . "-" . $arr1[$i]."-". $arr2[$i] ;

}

Do not nest the loops; 不要嵌套循环;

Use one loop and print array1[i]."-".array2[i] 使用一个循环并打印array1 [i]。“-”。array2 [i]

You can use for loop instead of foreach too: 您也可以使用for循环而不是foreach:

$arr1=array(32,45,67,89);
$arr2=array(5,3,2,1);    
for ($i = 0; $i < 4; $i++) {
    echo $arr1[$i] . "-" . ($i+1) . "-" . $arr2[$i];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM