我有一個功能,接受($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