2014-07-01 15 views
1

我有一個int類型的php變量$a。現在如果$a=1;那麼前兩個選項只應該是可見的,如果$a=2;那麼前三個選項應該只顯示等等。我怎樣才能做到這一點?控件選擇表格上的選項數

echo "<form class='form-horizontal'> 
     <fieldset > 
      <span class='control-group' > 
      <span class='controls'> 
       <select id='fl' class='form-control' style='cursor:pointer;'> 
        <option " . ($default == 0 ? "selected='selected'" : "") . " style='display:none;' value='0'>Select</option> 
        <option " . ($default == 1 ? "selected='selected'" : "") . " value='1'>Option1</option> 
        <option " . ($default == 2 ? "selected='selected'" : "") . " value='2'>Option2</option> 
       </select> 

      </span> 
     </span> 
     <div><button id='mybtn' type='button'>Save</button></div> 
     </fieldset> 
    </form>"; 

回答

0

在一個變量將選擇基於$aecho前和使用該變量在echo

<?php 
$options = ''; 

if($a==1) 
{ 
    $options = "<option " . ($default == 0 ? "selected='selected'" : "") . " style='display:none;' value='0'>Select</option> 
       <option " . ($default == 1 ? "selected='selected'" : "") . " value='1'>Option1</option>"; 
} 
else if($a==2) 
{ 
    $options = "<option " . ($default == 0 ? "selected='selected'" : "") . " style='display:none;' value='0'>Select</option> 
       <option " . ($default == 1 ? "selected='selected'" : "") . " value='1'>Option1</option> 
       <option " . ($default == 2 ? "selected='selected'" : "") . " value='2'>Option2</option>"; 
} 

echo "<form class='form-horizontal'> 
     <fieldset > 
      <span class='control-group' > 
      <span class='controls'> 
       <select id='fl' class='form-control' style='cursor:pointer;'> 
        ".$options." 
       </select> 

      </span> 
     </span> 
     <div><button id='mybtn' type='button'>Save</button></div> 
     </fieldset> 

    </form>"; 
?> 
+0

thanks..that工作,但使用你的答案後,我想出了一個稍微優雅的解決方案:if($ a> = 1){echo「 Option1」; if($ a> = 2){echo「 Option2」; }} – user3774008

1

似乎是一個for環的絕佳機會。

// put your values into an array for easy access inside the loop 
$options = array(
    1 => "Option1", 
    2 => "Option2", 
    3 => "Option3", 
    etc... 
); 

// output the beginning of the <select> html 
echo "<select id='fl' class='form-control' style='cursor:pointer;'> 
     <option " . ($default == 0 ? "selected='selected'" : "") . " style='display:none;' value='0'>Select</option>"; 

// loop through items until we reach our limit, set in $a 
for ($i = 1; $i < $a; $i++) { 
    echo "<option " . ($default == $i ? "selected='selected' " : "") . "value='" . $i . "'>" . $options[i] . "</option>"; 
} 

// output the end of the <select> html to close it off 
echo "</select>"