我有两个数组。第一个数组是名称,它有 5 个名称。第二个数组是组,它有 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
先感谢您
最佳答案
我们假设数组是数字索引的(从 0 开始),并且没有跳过索引(即 $group
数组始终定义为 range(1, $n);
)。
然后,您可以针对该数组的长度使用模数运算符 %
,如下所示。
foreach ($names as $index => $name) {
$result = "The student: " . $name . " belongs to group " .$groups[$index % count($groups)]. ".\n";
echo $result;
}
关于如果一个数组的索引是最后一个倒带数组,则 PHP 循环两个数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55516054/