在PHP中生成日期数组

时间:2015-03-12 00:42:53

标签: php arrays

我试图在PHP页面中生成一种选择日期的粗略方法, 非常原始,但这是我被要求制作的。

基本上我试图在HTML中生成一个选择下拉列表,其中包含一系列日期(以dd / mm / yyyy格式)

它将包括今天的日期(2015年3月12日),范围将是从今天起的10天,但是需要一些如何遵循标准日历(例如31或30)几个月......)

这可以吗?如果是这样,有人可以帮助我

1 个答案:

答案 0 :(得分:1)

看看DatePeriod。您可以创建一个DatePeriod并在其上进行映射以创建日期数组,如下所示:

// create DatePeriod with the following arguments:
//
// * DateTime for current datetime
// * DateInterval of 1 day
// * Recurrences - today's date *plus* this number of repeated dates
$period = new DatePeriod(new DateTime(), new DateInterval('P1D'), 9);

// Convert DatePeriod to array of DateTime objects
// Map over array
// Build array of formatted date strings
$dates = array_map(function($dt) {
    return $dt->format('d/m/Y');
}, iterator_to_array($period));

// Done :)
var_dump($dates);

这会产生类似的结果:

array (size=11)
  0 => string '12/03/2015' (length=10)
  1 => string '13/03/2015' (length=10)
  2 => string '14/03/2015' (length=10)
  3 => string '15/03/2015' (length=10)
  4 => string '16/03/2015' (length=10)
  5 => string '17/03/2015' (length=10)
  6 => string '18/03/2015' (length=10)
  7 => string '19/03/2015' (length=10)
  8 => string '20/03/2015' (length=10)
  9 => string '21/03/2015' (length=10)

请注意,重复次数少一次,因为它不包括开始日期。

希望这会有所帮助:)