使用 php 在 select 元素中设置默认选项

Set default option in select-element using php

我正在寻找一种简单的方法来动态更改 select 元素中的默认项,而无需在每个选项元素中添加大量代码。
这是一个 select 元素的示例,它允许您 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>

如您所见,其中的代码太多了。

我想知道你们中是否有人对如何执行此操作有更好的想法。

使用循环:

<?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>

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

<?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>

使用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>

可能会有帮助..