如果一个数组的索引是最后一个倒带数组,则PHP循环两个数组
我有两个数组。第一个数组是names,它有5个名称。第二个数组是groups,它有3个组。我想循环遍历这两个数组,并将每个索引名设置为索引组。如果组索引完成,我想重新启动第二个数组 如果组索引到达最后一项,我尝试将其重置为0,但无效如果一个数组的索引是最后一个倒带数组,则PHP循环两个数组,php,arrays,foreach,Php,Arrays,Foreach,我有两个数组。第一个数组是names,它有5个名称。第二个数组是groups,它有3个组。我想循环遍历这两个数组,并将每个索引名设置为索引组。如果组索引完成,我想重新启动第二个数组 如果组索引到达最后一项,我尝试将其重置为0,但无效 $names = [ 'John', 'Jane', 'George', 'Jim', 'Jack' ]; $groups = [ '1', '2', '3' ]; foreach ($names as $index =>
$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>";
}
提前谢谢您可以对组索引进行模块化
$groups[$index%sizeOf($groups)]
我们假设数组是数字索引的(从0开始),并且没有跳过的索引(即$group
数组始终定义为范围(1,$n);
)
然后可以对该数组的长度使用模运算符%
,如下所示
foreach ($names as $index => $name) {
$result = "The student: " . $name . " belongs to group " .$groups[$index % count($groups)]. ".\n";
echo $result;
}
- 现场演示
试试这个!在这段代码中,如果您添加了一个新的组,就不会有问题
<?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>";
}
这适用于任何类型的数组
$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))
)
)
);
你能在这里分享你的预期成果吗
foreach ($names as $index => $name) {
$result = "The student: " . $name . " belongs to group " .$groups[$index % count($groups)]. ".\n";
echo $result;
}
<?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>";
}
$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))
)
)
);