如果使用数组,则在下拉列表中获取选定月份值

时间:2013-05-28 07:07:16

标签: php arrays date select option

我试图在下拉菜单中获取所选值;但它里面的项目是一个数组。如何获取所选选项的值?

目前,我有以下几行代码:

<?php
// lowest year wanted
$cutoff = 2013;

// current year
$now = date('Y');

// build months menu
echo '<select name="month">' . PHP_EOL;
for ($m=1; $m<=12; $m++) {
    echo '  <option value="' . $m . '">' . date('M', mktime(0,0,0,$m)) . '</option>' . PHP_EOL;
}
echo '</select>' . PHP_EOL;

// build days menu
echo '<select name="day">' . PHP_EOL;
for ($d=1; $d<=31; $d++) {
    echo '  <option value="' . $d . '">' . $d . '</option>' . PHP_EOL;
}
echo '</select>' . PHP_EOL;

// build years menu
echo '<select name="year">' . PHP_EOL;
for ($y=$now; $y>=$cutoff; $y--) {
    echo '  <option value="' . $y . '">' . $y . '</option>' . PHP_EOL;
}
echo '</select>' . PHP_EOL;
?>

比方说,我本月选了七月。如何告诉浏览器我选择了7月。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

试试这个

echo '<select name="month">' . PHP_EOL;
for ($m=1; $m<=12; $m++) {
    if($sel_mnth == $m)
        echo '  <option value="' . $m . '" selected="selected">' . date('M', mktime(0,0,0,$m)) . '</option>' . PHP_EOL;
    else   
        echo '  <option value="' . $m . '">' . date('M', mktime(0,0,0,$m)) . '</option>' . PHP_EOL;
}
echo '</select>' . PHP_EOL;

或直接

for ($m=1; $m<=12; $m++) {                   
        echo '  <option value="' . $m . '" if($sel_mnth == $m) echo "selected=\'selected\'";>' . date('M', mktime(0,0,0,$m)) . '</option>' . PHP_EOL;
}

答案 1 :(得分:2)

select放在form标记内,并在提交表单后使用 $_POST['month']$_POST['year']用于获取月份和年份用户选择的值。

像这样

if (isset($_POST['submit'])){

$year=$_POST['year']; //user selected year value is here
...
}

<form method="POST" action="">
... //here is your select tag codes
...
<input type="submit" name="submit" />
</form>

答案 2 :(得分:0)

<select>
    <option value="">--Select Month--</option>
    <?php for ($i=1; $i<=12; $i++)
    {
        ?>
            <option value="<?php echo $i;?>"><?php echo $i;?></option>
        <?php
    } ?>

</select>