PHP:循环创建前12个月的列表

时间:2014-04-03 19:50:28

标签: php date for-loop foreach

有没有一种方法可以使用PHP循环根据当前月份(当前月份除外)创建一个类似以下的列表,其中包含前12个月的列表? 该值应该始终是该月的第一个(格式:yyyy-mm-dd),下拉列表本身应该只显示年份和月份(格式:yyyy-mm):

<option value="2014-03-01">2014-03</option>
<option value="2014-02-01">2014-02</option>
<option value="2014-01-01">2014-01</option>
<option value="2013-12-01">2013-12</option>
<option value="2013-11-01">2013-11</option>
<option value="2013-10-01">2013-10</option>
//...

我尝试了以下但似乎有些不对劲,因为这不起作用:

<?php for ($i=0; $i<=12; $i++) { ?>
    <option value="<?php echo date('Y-m-d', strtotime("-1 month")); ?>"><?php echo date('Y-m', strtotime("-1 month")); ?></option>
<? } ?>

非常感谢你提供任何帮助,蒂姆。

5 个答案:

答案 0 :(得分:4)

$start    = (new DateTime('1 year ago'))->modify('first day of this month');
$end      = (new DateTime())->modify('first day of this month');
$interval = new DateInterval('P1M');
$period   = new DatePeriod($start, $interval, $end);

$months = array();
foreach ($period as $dt) { 
    $months[$dt->format('Y-m-d')] = $dt->format('Y-m');
}
$reverse_months = array_reverse($months);
print_r($reverse_months);

Demo

然后您可以遍历$ reverse_months来创建下拉列表

foreach($reverse_months as $key => $value) {
?>
    <option value="<?php echo key; ?>"><?php echo value; ?></option>
<?php
}

我们必须使用array_reverse()的原因是DatePeriod只能及时推进。

答案 1 :(得分:4)

<?php
for ($i=0; $i<=12; $i++) { 
echo '<option value="'.date('Y-m-d', strtotime("-$i month")).'">'.date('Y-m', strtotime("-$i month")).'</option>';
 } 

答案 2 :(得分:2)

您可以使用datetime扩展名来创建迭代器。这很简单:

// This is when to start counting
$start = new DateTime('now');

// The interval; i.e. every time we iterate we should get
// the first day of the previous month
$interval = DateInterval::createFromDateString('first day of last month');

// The period (or the iterator) should go for twelve
// months and the start date should not be included
$period = new DatePeriod($start, $interval, 12, DatePeriod::EXCLUDE_START_DATE);

// The DatePeriod class implements the Traversable
// interface and can therefore be used in a foreach loop
foreach($period as $time) {
    $val = $time->format("Y-m-d");
    $txt = $time->format("Y-m");
    echo "<option value=\"{$val}\">{$txt}</option>\n";
}

答案 3 :(得分:1)

这就是我所使用的,它有点简陋,但即使你到月底也能工作......不像Glavić指出的那样接受答案:

attendance__is_present=False

答案 4 :(得分:-2)

将-1更改为$i以反映并存储它以供双重使用。

<?php 
    for ($i=1; $i>=12; $i++) { 
        $last = strtotime("-$i month");
?>
    <option value="<?php echo date('Y-m-d', $last);?>"><?php echo date('Y-m', $last);?></option>
 <? } ?>