虽然我不理解您对循环的厌恶,但我确实理解尽可能地隐藏代码。
为此,我将扩展 PHP 的DateTime对象以提供您所追求的功能。像这样的东西: -
class MyDateTime extends DateTime
{
/**
* Creates an array of date strings of all days between
* the current date object and $endDate
*
* @param DateTime $endDate
* @return array of date strings
*/
public function rangeOfDates(DateTime $endDate)
{
$result = array();
$interval = new DateInterval('P1D');
//Add a day as iterating over the DatePeriod
//misses the last day for some strange reason
//See here http://www.php.net/manual/en/class.dateperiod.php#102629
$endDate->add($interval);
$period = new DatePeriod($this, $interval, $endDate);
foreach($period as $day){
$result[] = $day->format('Y-m-j');
}
return $result;
}
}
然后当你想使用它时,你可以这样做:-
$st_date = new MyDateTime("2012-07-20");
$en_date = new DateTime("2012-07-27");
$dates = $st_date->rangeOfDates($en_date);
var_dump($dates);
将给出以下输出:-
array
0 => string '2012-07-20' (length=10)
1 => string '2012-07-21' (length=10)
2 => string '2012-07-22' (length=10)
3 => string '2012-07-23' (length=10)
4 => string '2012-07-24' (length=10)
5 => string '2012-07-25' (length=10)
6 => string '2012-07-26' (length=10)
7 => string '2012-07-27' (length=10)
虽然,不幸的是,您可能需要一个循环来迭代该数组:)
显然,该解决方案使用循环来实现其目标,但它们被封装在一段可重用的代码中。
有关更多信息,请参阅有关DateTime、DateInterval和DatePeriod的 PHP 手册。这些页面的评论中有很多提示。