我有一个功能,接受($year, $month = null, $day = null)
优化mysql日期生成器?
基本上一年总是必须通过,但月和日是可选的。
如果他们没有通过,那么它将范围设置为尽可能最大。
这样:call | result
(2012, 08, 15) | ['2012-08-15', '2012-08-15']
(2012, 08) | ['2012-08-01', '2012-08-31']
(2012, 02) | ['2012-02-01', '2012-02-29']
(2012) | ['2012-01-01', '2012-12-31']
() | false
我有下面的代码,但是对我来说,似乎不必要的复杂性,任何人都可以想出一个更好的版本?
if (!is_null($year)) {
//year
$from = $year . '-';
$to = $year . '-';
//month
if (!is_null($month)) {
$from .= sprintf('%02d', $month) . '-';
$to .= sprintf('%02d', $month) . '-';
//day
if (!is_null($day)) {
$from .= sprintf('%02d', $day);
$to .= sprintf('%02d', $day);
} else {
$from .= '01';
$to .= sprintf('%02d', cal_days_in_month(CAL_GREGORIAN, $month, $year));
}
} else {
$from .= '01-31';
$to .= '12-31';
}
return array($from, $to);
}
return false;
这有一个缺陷。也许它可以在顶部使用'array(-1 => $ year)'。 – hakre 2012-08-15 10:04:41
缺陷在哪里? – DavidS 2012-08-15 10:06:46
比较数组联合运算符的作用:http://php.net/manual/en/language.operators.array.php - 您正在覆盖年份数组键。 – hakre 2012-08-15 10:12:14