"2013", "mo-6ren">
gpt4 book ai didi

php - 在数年中获取数月的最有效方法

转载 作者:可可西里 更新时间:2023-11-01 00:03:00 25 4
gpt4 key购买 nike

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

例如 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);
}

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

最佳答案

你可以试试

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
)

)

关于php - 在数年中获取数月的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15121884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com