有没有办法在数组中间启动foreach循环?

时间:2019-02-05 02:58:56

标签: php

我有几个月的时间。我想遍历每个月作为获取每个值的关键,但是...

我想从本月开始,运行foreach,然后回到第二年,直到第12个月为止。

我曾尝试根据当月创建一个单独的月数组,但这似乎有点不方便。

3 个答案:

答案 0 :(得分:4)

您可以将do/while循环与模计数器一起使用,例如

$months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
$i = $current_month = 5;
do {
    echo $months[$i] . "\n";
    $i = ($i + 1) % 12;
} while ($i != $current_month);

输出:

Jun 
Jul 
Aug 
Sep 
Oct 
Nov 
Dec 
Jan 
Feb 
Mar 
Apr 
May

Demo on 3v4l.org

如果还需要维护年份计数器,则可以使用以下代码,当月份结束时,该代码将递增年份:

$year = 2018;
$i = $current_month = 5;
do {
    echo $months[$i] . " $year\n";
    $i = ($i + 1) % 12;
    if ($i == 0) $year++;
} while ($i != $current_month);

输出:

Jun 2018
...
Dec 2018
Jan 2019
...
May 2019

Demo on 3v4l.org

答案 1 :(得分:1)

您可以尝试使用continue语句!

$current_month = 6; # just assuming, you can change as per your requirement.
foreach ($month_array as $k => $v) {
   if ($k < 5) continue;
   // your code here to go after your current month to end of the year's month
}

答案 2 :(得分:1)

为什么不使用for语句?

$months = [
   'January', 
   'February',
   '...',
];

$currentMonth = 5; // 0 for January, 11 for December

for($i = 0; $i < 12; $i++) {
    $index = ($currentMonth + $i) % 12;

    echo $months[$index] . PHP_EOL;
}

将打印

June
July
August
September
...