我正在创建一个函数,您可以在其中给出起始年、月和结束年、月,并且该函数将在两个给定点之间的每个月和年打印。
我已经创建了一个可以完美运行的函数,但我相信这不是一个好的做法,可能有更好的方法来做到这一点。现在我正在寻求您的帮助以找到更好的方法。
PS 我无法获取完整日期作为输入。只能获取月份和年份。
这是我的代码 -
function get_all_months($monthstart = null, $yearstart = null, $monthend = null, $yearend = null) {
if (($monthstart === null) || ($yearstart === null) || ($monthend === null) || ($yearend === null)) {
$monthend = date('m');
$yearend = date('Y');
if($monthend < 6) {
$yearstart = $yearend - 1;
$monthstart = (($monthend - 5) + 12);
} else {
$yearstart = $yearend;
$monthstart = $monthend - 5;
}
}
$month_array = array();
if ($yearstart > $yearend) {
for ($m=$monthend; $m<=12; $m++) $month_array[] = array('month' => $m, 'year' => $yearend);
for ($y=$yearend+1; $y<$yearstart; $y++) for ($m=1; $m<=12; $m++) $month_array[] = array('month' => $m, 'year' => $y);
for ($m=1; $m<=$monthstart; $m++) $month_array[] = array('month' => $m, 'year' => $yearstart);
} elseif ($yearend > $yearstart) {
for ($m=$monthstart; $m<=12; $m++) $month_array[] = array('month' => $m, 'year' => $yearstart);
for ($y=$yearstart+1; $y<$yearend; $y++) for ($m=1; $m<=12; $m++) $month_array[] = array('month' => $m, 'year' => $y);
for ($m=1; $m<=$monthend; $m++) $month_array[] = array('month' => $m, 'year' => $yearend);
} else {
for ($m=$monthstart; $m<=$monthend; $m++) $month_array[] = array('month' => $m, 'year' => $yearstart);
}
return $month_array;
}
编辑:根据 Nigel Ren 的回答,这是我能想到的最好的方法 -
function get_all_months($monthstart = null, $yearstart = null, $monthend = null, $yearend = null) {
if (($monthstart === null) || ($yearstart === null) || ($monthend === null) || ($yearend === null)) {
$monthend = date('m');
$yearend = date('Y');
if($monthend < 6) {
$yearstart = $yearend - 1;
$monthstart = (($monthend - 5) + 12);
} else {
$yearstart = $yearend;
$monthstart = $monthend - 5;
}
}
牛魔王的故事
胡说叔叔
墨色风雨
HUWWW
函数式编程