foreach循环不会超过范围的开始

I am trying to build a loop that echoes each month of the year until the current month. My foreach loop just stays on the start and doesn't progress through the rest of the range. Here is my code:

$startMonth = '01';
$endMonth = date('m');

foreach (range($startMonth, $endMonth) as $month) {
    $dataValue = date('n', $month);
    echo '<td class="month" data-value="';
    echo $dataValue;
    echo '" data-id="' . $incrementYear . '"><a href="/Archive/view/';
    echo $incrementYear;
    echo '/';
    echo date('m', $month);
    echo '">';
    echo date('F', $month);
    echo '</a></td>';
}

Here is the output:

January    January    January    January    January    January

Each of the months has the correct link for what January should have, but for some reason, the range never leaves "01" which is the $startMonth and I'm not sure why. I was thinking it had something to do with integer vs. string, but removing the ' from $startMonth = '01'; to make it an integer, but that didn't work either.

As far as I understand them, I am using the range correctly.

What am I missing here?

EDIT

  • $dataValue can be commented out and I will still get January 6 times, its just the link will have a data-value different than what I want. This variable has no effect on the month itself.

  • If I change the bottom line of code from echo date('F', $month); to echo $month; I get:

    1    2    3    4    5    6
    

Problem is that to date() as timestamp you always pass 01, 02... and that converts to ~12 first seconds of Unix timestamp. So 1970-01-01 00:00:03 is January.

Change your code to use mktime

$dataValue = date('n', mktime(0, 0, 0, $month, 1, date('Y')));

$startMonth = '01';
$endMonth = date('m');

foreach (range($startMonth, $endMonth) as $month) {
    $time = mktime(0, 0, 0, $month, 1, date('Y'));
    $date = date('n', $time);
    $month = date('m', $time);
    $monthName = date('F', $time);

    echo "<td class='month' data-value='{$date}' data-id='{$incrementYear}'><a href='/Archive/view/{$incrementYear}/{$month}'>{$monthName}</a></td>";
}

Change the $dataValue from

$dataValue = date('n', $month);

to

$dateObj   = DateTime::createFromFormat('!m', $month);
echo $dateObj->format('F');

Hope this helps.

Try this:

$startMonth = '01';
$endMonth = date('m');

foreach (range($startMonth, $endMonth) as $month) { 
 $dataValue = date('F', mktime(0, 0, 0, $month, 1, date('Y')));
 $month = sprintf('%02d', $month);
 echo '<td class="month" data-value="' . $dataValue . '" data-id="' . $month . '"><a href="/Archive/view/' . $month . '">' . $dataValue . '</a></td>';
}

Output:

JanuaryFebruaryMarchAprilMayJune

Try Below Code:

$start_date = date('Y-01-01');
$end_date = date('Y-m-01');

$loop_date = $start_date;

//loop through months
while(strtotime($loop_date)<=strtotime($end_date)){

echo date('F',strtotime($loop_date));

$loop_date = date('Y-m-d', strtotime("+1 months", strtotime($loop_date)));

}