简体   繁体   中英

PHP How to reverse a month year dropdown menu generated with DatePeriod()

I have a dropdown menu generated as follow:

$start    = new DateTime('2014-06-01');
$end      = new DateTime(date('Y-m-d'));
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

$select_mois = '<select name="select_mois" id="select_mois">';  
    
foreach ($period as $dt) {
    $select_mois.="<option value=" . $dt->format("m-Y") . ">" . strftime('%m.%Y', $dt->format('U')) . "</option>";
}        

$select_mois.='</select>';

It works perfectly, but I get the older date first in my dropdown (Starting from 06.2014)

How do I reverse the menu to have the most recent date first?

Thanks for your help

iterate and reverse over as an array;

also strftime is now deprecated

<?php 
$start    = new DateTime('2014-06-01');
$end      = new DateTime(date('Y-m-d'));
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

$select_mois = '<select name="select_mois" id="select_mois">';  

$period = array_reverse(iterator_to_array($period));
    
foreach ($period as $dt) {
    $select_mois.="<option value=" . $dt->format("m-Y") . ">" . $dt->format('m.Y') . "</option>";
}        

$select_mois.='</select>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM