3

从指定日期到现在,按年份分组的月份数组的最有效方法是什么。

例如 getMonths("August 2012") 将输出

array(
    array("Year"=>"2013", "months" = array(
         "February", "January")
    ),
    array("Year"=>"2012", "months" = array(
         "December", "November","October", "September", "August")
    )
)

到目前为止,我有:

$start = strtotime('2012-08-01');
$end = time();
$month = $start;
$months[] = date('F', $start);
while($month <= $end) {
  $month = strtotime("+1 month", $month);
  $months[] = date('F', $month);
}

这是输出正确的月份,但没有将它们分组为年份。谢谢

4

2 回答 2

11

你可以试试

function getMonths($month,$count = 1) {
    $now = new DateTime();
    $start = DateTime::createFromFormat("F Y", $month);
    $list = array();
    $interval = new DateInterval(sprintf("P%dM",$count));
    while ( $start <= $now ) {
        $list[$start->format("Y")][] = $start->format("F");
        $start->add($interval);
    }
    return $list;
}

print_r(getMonths("August 2012"));

输出

Array
(
    [2012] => Array
        (
            [0] => August
            [1] => September
            [2] => October
            [3] => November
            [4] => December
        )

    [2013] => Array
        (
            [0] => January
            [1] => February
        )

)
于 2013-02-27T20:43:47.147 回答
0

由于此处发布的答案对我不起作用(确定还尝试了在线沙箱),我编写了一个适用于大多数 PHP 版本的方法:

function getMonths($monat, $year) {
        $list = array();
        for(;$monat <= 12;$monat++) {
            if($year == date("Y") && $monat == date("m")) {     // exit on current month+year
                break;
            }
            if(!isset($list[ $year ])) {
                $list[ $year ] = array();
            }
            $list[ $year ][ str_pad($monat, 2, '0', STR_PAD_LEFT) ] = date("F", strtotime('01.' . $monat . '.' . $year));

            if($monat == 12) {
                $monat = 0;
                $year++;
            }
        }
        return $list;
    }
于 2014-09-16T11:49:32.893 回答