根据变量更改“if”语句

时间:2012-07-16 04:21:39

标签: php variables if-statement

如何在不为每个案例编写新语句的情况下更改基于变量的“if”语句?我的选择下拉列表“时间轴”将填充25个以上的选项,所以我想在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>';
                }
}

2 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分: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>';
    }