动态选择下拉菜单

时间:2016-02-12 17:06:13

标签: php html

我有一个包含3个选项的菜单,最简单的形式如下:

<form action="samePageAction" form="post">
  <select>
    <option>Yes</option>
    <option>No</option>
    <option>Maybe</option>
  </select>
</form>

它不是真正的动态&#34;,它只是基于用户在数据库中的设置,我选择了什么&#34;选项&#34;默认显示:

    <form action="samePageAction" form="post">
      <select>
<?    
      if(!$personUndecided && $personHasAgreed){
?>   
        <option>Yes</option>
        <option>No</option>
        <option>Maybe</option> 
<?    
      } else if(!$personUndecided && !$personHasAgreed){
?> 
        <option>No</option>
        <option>Yes</option>
        <option>Maybe</option>
      </select>
<?
      else {
?>
        <option>Maybe</option>
        <option>Yes</option>
        <option>No</option>
     </select>
<? } ?>
    </form>

&#34;第一&#34;每种情况下的选项都很重要,因为当表单被禁用时,这是用户将看到的选项。当我看到这个时,我感到很粗鲁,但更好的解决方案并没有找到我。如何优化此菜单?

问题:我怎样才能防止这么重复自己。或者这段代码看起来很正常吗?

3 个答案:

答案 0 :(得分:1)

您可以通过这种方式缩短代码,例如:

<?php
   if( $personHasAgreed )      $choices = array ( 'Yes',  'No',  'Maybe' );
   elseif( !$personHasAgreed ) $choices = array ( 'No',   'Yes', 'Maybe' );
   else                        $choices = array ( 'Maybe','Yes', 'No' );

   foreach( $choices as $choice ):
?>
       <option><?php echo $choice; ?></option>
<?php endforeach; ?>

通过这种方式,您可以根据$personHasAgreed设置首先分配各种选项值,然后执行一个foreach循环以输出每个选项。

编辑:请注意,我认为永远不会执行else语句......

答案 1 :(得分:1)

使用explode函数的简单解决方案:

<form action="samePageAction" form="post">
    <select>
<?php
    $personHasAgreed = "";
    $valueString = ($personHasAgreed === 1)? "Yes,No,Maybe" : (($personHasAgreed === 0)? "No,Yes,Maybe" : "Maybe,Yes,No" );
    $valueString = explode(",", $valueString); 
    foreach($valueString as $word){
        echo "<option>". $word ."<option>";
    }
?>     
      </select>
  </form>

答案 2 :(得分:0)

这样的东西?

<form action="samePageAction" method="post">
    <select>
<?php
$possAnswer = array(
    "1" => "<option>Yes</option>", 
    "0" => "<option>No</option>", 
    "2" => "<option>Maybe</option>"
    );
if($personHasAgreed) {
    echo $possAnswer[1] . $possAnswer[0] . $possAnswer[2];
} else if(!$personHasAgreed ){
    echo $possAnswer[0] . $possAnswer[1] . $possAnswer[2];
} else {
    echo $possAnswer[2] . $possAnswer[1] . $possAnswer[0];
}
?> 
    </select>
</form>

`