2012-07-16 95 views
0

如何在不爲每個案例編寫新語句的情況下更改基於變量的「if」語句?我的選擇下拉菜單 「時間表」 將與25+選項進行填充,所以我想使if語句在PHP腳本根據變量更改「if」語句

HTML設置變量:

<p>Current Status: </p> <select name="timeline" id="timeline"> 
      <option value="completed" selected>Completed</option> 
      <option value="active">Active</option> 
</select> 

PHP:

 $current_state = $_POST['timeline']; 
    $current = strtotime("now"); 

while($row = mysql_fetch_array($results)){ 




     if($current_state == "completed"){ 
      $end = strtotime($row['End']); 

      $my_if = "if($current > $end){"; 

     } 

     if($current_state == "active"){ 

      $end = strtotime($row['End']); 
      $start = strtotime($row['Start']); 

      $my_if = "if($start < $current && $end > $current){"; 

     } 
       //THIS IS WHERE THE IF STATEMENT WOULD BE USED 
       echo $my_if; 

          echo '<tr> 
          <td>'. $row['ID'] .'</td> 
          <td>'. $row['Name'] .'</td> 
          <td>'. $row['LastName'] .'</td> 

         </tr>'; 
       } 
} 

回答

1

將您的「meta-if」的條件包含在if本身中:

if ($current_state == "completed") 
    { 
    $end = strtotime($row['End']); 
    } 

if ($current_state == "active") 
    { 
    $end = strtotime($row['End']); 
    $start = strtotime($row['Start']); 
    } 

if (($current_state == "completed" && $current > $end) || ($current_state == "active" && $start < $current && $end > $current)) 
    { 
    echo '<tr> 
    <td>'. $row['ID'] .'</td> 
    <td>'. $row['Name'] .'</td> 
    <td>'. $row['LastName'] .'</td> 
    </tr>'; 
    } 
+0

非常有用的感謝您的幫助。 +1 – Denoteone 2012-07-16 04:35:19

+0

由於額外的if語句,這實際上較慢。 – Geoffrey 2012-07-16 22:33:27

+2

從一些額外的if語句中放慢速度是微不足道的。 – Zombaya 2012-07-16 22:44:17

2

你應該完全重做你的邏輯

$completed = $_POST['timeline'] == 'completed'; 
while($row = mysql_fetch_array($results)) { 
    $end = strtotime($row['End']); 
    if (!$completed) 
     $start = strtotime($row['Start']); 

    if (
     ($completed && $current > $end) || 
     (!$completed && $start < $current && $end > $current) 
    ) { 
     // do stuff 
    } 
} 
+0

太好了。這是非常有用的,現在有意義。感謝您的幫助+1 – Denoteone 2012-07-16 04:34:35