使用php在select-element中设置默认选项

时间:2015-02-27 14:40:59

标签: php html select default

我正在寻找一种简单的方法来动态更改select-element中的默认项,而不会在每个option-element中添加大量代码。
这是一个select元素的示例,它允许您选择月份,并始终将当前月份设置为默认项目:

    <select name="month">
        <option <?php echo ((date("n")==1)?'selected="selected"':'')?> value="1">Januar</option>
        <option <?php echo ((date("n")==2)?'selected="selected"':'')?> value="2">Februar</option>
        <option <?php echo ((date("n")==3)?'selected="selected"':'')?> value="3">M&auml;rz</option>
        <option <?php echo ((date("n")==4)?'selected="selected"':'')?> value="4">April</option>
        <option <?php echo ((date("n")==5)?'selected="selected"':'')?> value="5">Mai</option>
        <option <?php echo ((date("n")==6)?'selected="selected"':'')?> value="6">Juni</option>
        <option <?php echo ((date("n")==7)?'selected="selected"':'')?> value="7">Juli</option>
        <option <?php echo ((date("n")==8)?'selected="selected"':'')?> value="8">August</option>
        <option <?php echo ((date("n")==9)?'selected="selected"':'')?> value="9">September</option>
        <option <?php echo ((date("n")==10)?'selected="selected"':'')?> value="10">Oktober</option>
        <option <?php echo ((date("n")==11)?'selected="selected"':'')?> value="11">November</option>
        <option <?php echo ((date("n")==12)?'selected="selected"':'')?> value="12">Dezember</option>
      </select>

正如您所看到的,其中包含太多代码。

我想知道你是否有人更了解如何做到这一点。

3 个答案:

答案 0 :(得分:1)

使用循环:

<?php
$months = [
    1=>'January',
    2=>'february',
    3=>'march'
    ....//etc
];
?>

<select name="month">
    <?php foreach($months as $key=>$month):?>
        <option <?= ((date("n")==$key)?'selected="selected"':'')?> value="<?= $key;?>"><?= $month;?></option>
    <?php endforeach;?>
</select>

答案 1 :(得分:1)

你可以创建一个月数组,然后像那样检查它。

<?php
 $months = array(
  array(
    "monthNumber" => 1,
    "name" => "January"
  ),
  array(
    "monthNumber" => 2,
    "name" => "Feb"
  ),
  array(
    "monthNumber" => 3,
    "name" => "March"
  )
);
?>

<select name="month">
 <?php
  foreach ($months as $month) {
   echo "<option " . ((date("n") == $month['monthNumber']) ? 'selected="selected"' : ''). ">".$month['name']."</option>";
  }
 ?>
</select>

答案 2 :(得分:1)

使用foreach循环

    <?php
    $months=array('1'=>'January','2'=>'Febuary','3'=>'March',4=>'April','5'=>'May','6'=>'June','7'=>'July','8'=>'August','9'=>'September',10=>'October','11'=>'November','12'=>'December');
    ?>
    <select name='month'>
    <?php foreach($months as $num=>$month) {?>
     <option <?php echo ((date("n")==$num)?'selected="selected"':'')?>value="<?php echo $num;?>"><?php echo $month; ?>
    </option> 
   </select>

可能有帮助..