Spy*_*Spy 4 php arrays foreach
我有两个数组。第一个数组是名称,它有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>";
}
Run Code Online (Sandbox Code Playgroud)
当它到达第四个名称项时,分组项应为1。是否可以进行这种思考?
预期结果
John - 1
Jane - 2
George - 3
Jim - 1
Jack - 2
Run Code Online (Sandbox Code Playgroud)
先感谢您
我们假设该数组已进行数字索引(从0开始),并且没有跳过的索引(即该$group数组始终定义为range(1, $n);)。
然后,可以%针对该数组的长度使用模数运算符,如下所示。
foreach ($names as $index => $name) {
$result = "The student: " . $name . " belongs to group " .$groups[$index % count($groups)]. ".\n";
echo $result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |