当一个数组的索引是最后一个时,PHP如何循环遍历两个数组。

4
我有两个数组。第一个数组是names,其中包含5个名称。第二个数组是groups,其中包含3个分组。我想循环遍历这两个数组,并将每个索引名称设置为索引组。如果组索引完成,则希望重新开始第二个数组。
我尝试在达到最后一项时将组索引重置为0,但它不起作用。
$names = [
  'John',
  'Jane',
  'George',
  'Jim',
  'Jack'
];

$groups = [
  '1',
  '2',
  '3'
];

foreach ($names as $index => $name) {
   $result = "The student: " . $name . " belongs to the: " .$groups[$index]. "group" ;
   echo ($result);
   echo "<br>";
   echo "<br>";
}

当达到第四个名称项时,组项应为1。有没有办法做到这一点?

期望产出

John - 1

Jane - 2

George - 3

Jim - 1

Jack - 2

提前感谢你


1
你能在这里分享你期望的输出吗? - Ankur Tiwari
4个回答

6
我们假设该数组是按数字索引排列的(从0开始),并且不存在跳过的索引(即$group数组始终定义为range(1, $n);)。
然后,您可以使用模运算符%来对该数组的长度进行操作,如下所示。
foreach ($names as $index => $name) {
   $result = "The student: " . $name . " belongs to group " .$groups[$index % count($groups)]. ".\n";
   echo $result;
}

4

您可以使用取模运算符%来对组进行索引。

$groups[$index % sizeOf($groups)]

<?php
$names = [
  'John',
  'Jane',
  'George',
  'Jim',
  'Jack'
];

$groups = [
  '1',
  '2',
  '3'
];

foreach ($names as $index => $name) {
   $result = "The student: " . $name . " belongs to the: " .$groups[$index%sizeOf($groups)]. "group" ;
   echo ($result);
   echo "<br>";
   echo "<br>";
}

结果: https://3v4l.org/LnOHAK


The student: John belongs to the: 1group<br><br>The student: Jane belongs to the: 2group<br><br>The student: George belongs to the: 3group<br><br>The student: Jim belo

0

试试这个!在这段代码中,如果你添加一个新的组,不会有任何问题。

<?php

$names = [
  'John',
  'Jane',
  'George',
  'Jim',
  'Jack'
];

$groups = [
  '1',
  '2',
  '3'
];

foreach ($names as $index => $name) {

   $result = "The student: " . $name . " belongs to the: " .$groups[$index % count($groups)]. "group" ;
   echo ($result);
   echo "<br>";
   echo "<br>";
}

0

这将适用于任何类型的数组

$names = [
  'John',
  'Jane',
  'George',
  'Jim',
  'Jack'
];

global $groups;

$groups = [
  '1',
  '2',
  '3'
];

$newArr = array_combine(
            $names, 
              array_merge(
                  $groups,
                  array_map(
                    function($v){
                      global $groups;
                      return $groups[$v%count($groups)]; 
                    }, 
                   array_keys(array_diff_key($names, $groups))
                 )
              )
          );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接