0

如何在不为每种情况编写新语句的情况下更改基于变量的“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>';
                }
}
4

2 回答 2

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
    }
}
于 2012-07-16T04:27:38.270 回答
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>';
    }
于 2012-07-16T04:26:12.950 回答