PHP:使用接下来12个月的名称填充数组

med*_*iev 7 php

for($x=0; $x<12; $x++)
{
    $month = mktime(0, 0, 0, date("m")+$x, date("d"),  date("Y"));
    $key = date('m', $month);
    $monthname = date('F', $month);
    $months[$key] = $monthname;
}
Run Code Online (Sandbox Code Playgroud)

我知道我确实错误地为mktime的第4个参数做了数学运算.我从当前月份数字(7月7月)开始,下个月每个月增加1,有时最终会导致同月返回两次,可能是因为我没有将它设置为月初?你会如何改进/重新编码?

结果是$ months将产生一个阵列,其中07 = 7月08 = 8月,09 = 9月.现在它填满了10月两次.我认为这与今天的第31次有关,它错误地添加到下个月.

dec*_*eze 26

只是略微修改你的代码,这应该工作得很好:

$months = array();
$currentMonth = (int)date('m');

for ($x = $currentMonth; $x < $currentMonth + 12; $x++) {
    $months[] = date('F', mktime(0, 0, 0, $x, 1));
}
Run Code Online (Sandbox Code Playgroud)

请注意,我拿出了数组键,因为我认为这是不必要的,但如果需要,你可以改变它.


小智 5

另一种方法是使用strtotime:

for ($x=0; $x < 12; $x++) {

    $time = strtotime('+' . $x . ' months', strtotime(date('Y-M' . '-01')));
    $key = date('m', $time);
    $name = date('F', $time);
    $months[$key] = $name;
}
Run Code Online (Sandbox Code Playgroud)

在我看来,这段代码更容易阅读.