选择当前月份的菜单,直到年底

时间:2011-09-14 04:59:43

标签: php

如何使用当月直到年底制作选择日期菜单?

例如......如果今天显示下拉列表,它将仅显示9月到12月作为用户的选项。

这是我到目前为止的代码,但它也显示了9月之前的几个月。

    <?php 
$curr_month = date("m");
$month = array (1=>"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$select = "<select name=\"month\">\n";
foreach ($month as $key => $val) {
    $select .= "\t<option val=\"".$key."\"";
    if ($key == $curr_month) {
        $select .= " selected=\"selected\">".$val."</option>\n";
    } else {
        $select .= ">".$val."</option>\n";
    }
}
$select .= "</select>";
echo $select;
?>

5 个答案:

答案 0 :(得分:3)

只需使用array_slice

即可
<?php 
$curr_month = date("m");
$month = array (1=>"January", "February", "March", "April", "May", "June", "July",   "August", "September", "October", "November", "December");
$month = array_slice($month, $curr_month-1);
$select = "<select name=\"month\">\n";
foreach ($month as $key => $val) {
    $select .= "\t<option val=\"".$key."\"";
    if ($key == $curr_month) {
        $select .= " selected=\"selected\">".$val."</option>\n";
    } else {
        $select .= ">".$val."</option>\n";
    }
}
$select .= "</select>";
echo $select;
?>

答案 1 :(得分:1)

$remaining = array_slice($month, date('n'));
foreach ($remaining as ...

答案 2 :(得分:1)

foreach ($month as $key => $val) {
if ($key >= date('n')){
...

答案 3 :(得分:1)

你有一个包含12个元素的数组。因此,获取当前月份的“数字”,减去一个,然后从阵列中的那个位置开始循环。

$start_loop_here = date('n')-1;

答案 4 :(得分:1)

$thisMonth = date('n');

$month = array (1=>"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$select = "<select name=\"month\">\n";
for ($monthCount = $thisMonth; $monthCount <= 12 ; $monthCount++) {
    $select .= "\t<option val=\"$monthCount\"";
    if ($monthCount == $thisMonth) {
        $select .= " selected=\"selected\">{$month[$monthCount]}</option>\n";
    } else {
        $select .= ">{$month[$monthCount]}</option>\n";
    }
}
$select .= "</select>";
echo $select;

@ cenanozen有一个更光滑的解决方案。修剪数组,然后迭代它。