2016-02-12 156 views
1

我有3個選項菜單,在最簡單的形式如下:動態選擇下拉菜單

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

,它只是根據用戶的數據庫中設置這是不是真的「動態」,我選擇什麼「選項」默認顯示:在每種情況下

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

「第一」的選擇是很重要的,因爲當表單被禁用,這是用戶將看到的選項。當我看到這件事情時,我感到非常痛苦,但更好的解決方案不會來到我身上。我怎樣才能優化這個菜單?

問題:如何防止重複自己這麼多。或者這段代碼看起來完全正常嗎?

+1

什麼,你居然找? *問題不清楚,親愛的* –

+1

@bruh請注意,'else'語句永遠不會執行 – fusion3k

+0

Thanks @ fusion3k,已修復。 – bruh

回答

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語句將永遠不會被執行...

+0

你太棒了! – bruh

+0

關於else塊,還有另外一個條件(我沒有提到),例如'$ personUndecided = true && $ personH​​asAgreed' ....只會遇到第三種情況,因爲前兩個將是錯誤的。感謝您指出,雖然! – bruh

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> 
+0

我也喜歡這個。謝謝!這真的很好 – bruh

+0

@bruh,不客氣 – RomanPerekhrest

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> 

`