我的天数等于10,并且我有一系列的工作日“星期一”,“星期二”,“星期三”,“星期四”,“星期五”。现在,我想将此数组重复10次。例如,如果days = 9,则该数组将打印出“星期一”,“星期二”,“星期三”,“星期四”,“星期五”,“星期一”,“星期二”,“星期三”,“星期四”
这是我已经尝试过的代码
$days = 9;
$arr = array("Monday", "Tuesday", "Wednesday", "Thursday", "Firday");
foreach (range(1, $days) as $i) {
foreach ($arr as $value) {
echo $value . ', ';
}
}
我回来的结果是
Monday, Tuesday, Wednesday, Thursday, Firday,
Monday, Tuesday, Wednesday, Thursday, Firday,
Monday, Tuesday, Wednesday, Thursday, Firday,
Monday, Tuesday, Wednesday, Thursday, Firday,
Monday, Tuesday, Wednesday, Thursday, Firday,
Monday, Tuesday, Wednesday, Thursday, Firday,
Monday, Tuesday, Wednesday, Thursday, Firday,
Monday, Tuesday, Wednesday, Thursday, Firday,
Monday, Tuesday, Wednesday, Thursday, Firday,
但是我期望的结果是
Monday, Tuesday, Wednesday,
Thursday, Firday, Monday, Tuesday, Wednesday, Thursday
答案 0 :(得分:1)
您要重复$days
次数组。您应该遍历数组$days
的索引。
$days = 13;
$arr = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
foreach (range(0, $days - 1) as $i) {
echo $arr[$i % 5] . ',';
};
答案 1 :(得分:0)
您可以只使用for
循环和模数运算符%
来确保索引不超出数组范围:
$days = 9;
$arr = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
for ($i = 0; $i < $days; $i++) {
echo $arr[$i % 5] . ',';
}
输出:
Monday,Tuesday,Wednesday,Thursday,Friday,Monday,Tuesday,Wednesday,Thursday,
如果您不希望尾随逗号,只需在循环结束前添加一个测试,然后将其输出即可:
for ($i = 0; $i < $days; $i++) {
echo $arr[$i % 5] . ($i == $days - 1 ? '' : ',');
}
输出:
Monday,Tuesday,Wednesday,Thursday,Friday,Monday,Tuesday,Wednesday,Thursday