dtxob80644 2018-06-25 06:38
浏览 20
已采纳

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
    
  • 写回答

4条回答 默认 最新

  • dsaaqdz6223 2018-06-25 06:46
    关注

    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>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制