我想知道在一个PHP页面上运行两个(或更多)if语句的最佳方法是什么。这是寻找机票类型和天数的表单的一部分。我需要在一个页面上运行这两个语句,我似乎没有工作,因为一旦它达到真正的声明,它就会停止。我怎样才能让它发挥作用?
<?php
if($ticket_type=='Child (5 & Under)'){
echo "
<select name=\"ticket_type[]\">
<option value=\"\">Select one...</option>
<option selected=\"selected\">Child (5 & Under)</option>
<option>Child (6 - 12)</option>
<option>Teen (13 - 17)</option>
</select>";
}else if($ticket_type=='Child (6 - 12)'){
echo "
<select name=\"ticket_type[]\">
<option value=\"\">Select one...</option>
<option>Child (5 & Under)</option>
<option selected=\"selected\">Child (6 - 12)</option>
<option>Teen (13 - 17)</option>
</select>";
}else if($ticket_type=='Teen (13 - 17)'){
echo "
<select name=\"ticket_type[]\">
<option value=\"\">Select one...</option>
<option>Child (5 & Under)</option>
<option>Child (6 - 12)</option>
<option selected=\"selected\">Teen (13 - 17)</option>
</select>";
}else{
echo "
<select name=\"ticket_type[]\">
<option value=\"\">Select one...</option>
<option>Child (5 & Under)</option>
<option>Child (6 - 12)</option>
<option>Teen (13 - 17)</option>
</select>";
}?>
<?php
if($days=='1 Day'){
echo "
<select name=\"ticket_type[]\">
<option value="">Select one...</option>
<option selected=\"selected\">1 Day</option>
<option>2 Days</option>
<option>3 out of 4 Days</option>
</select>";
}else if($days=='2 Days'){
echo "
<select name=\"ticket_type[]\">
<option value="">Select one...</option>
<option>1 Day</option>
<option selected=\"selected\">2 Days</option>
<option>3 out of 4 Days</option>
</select>";
}else if($days=='3 out of 4 Days'){
echo "
<select name=\"ticket_type[]\">
<option value="">Select one...</option>
<option>1 Day</option>
<option>2 Days</option>
<option selected=\"selected\">3 out of 4 Days</option>
</select>";
}else{
echo "
<select name=\"days[]\">
<option value="">Select one...</option>
<option>1 Day</option>
<option>2 Days</option>
<option>3 out of 4 Days</option>
</select>";
}?>
答案 0 :(得分:4)
您可以极大地简化代码:
$options = array(
'Select One' => 'Select One',
'1 Day' => '1 Day',
'2 Days' => '2 Days',
'3 or more' => '3 or More'
);
echo '<select name="ticket_type[]">';
foreach($options as $key => $val) {
$select = (($key == $days) ? ' selected="selected"' : '');
echo "<option value=\"", htmlspecialchars($key), "\"$select>", htmlspecialchars($val), "</option>";
}
echo '</select>';
这样,您只有一个指定了选项的位置,因此如果您将来需要添加更多选项,则只需更改该位置。现在你必须改变你的if()块的每一部分,这将变得乏味且容易出错。
答案 1 :(得分:1)
<select name="ticket_type[]">
<option value="">Select one...</option>
<option <? echo ($ticket_type == 'Child (5 & Under) ? 'selected="selected" : ''; ?>'>Child (5 & Under)</option>
<option <? echo ($ticket_type == 'Child (6 - 12) ? 'selected="selected" : ''; ?>>Child (6 - 12)</option>
<option <? echo ($ticket_type == 'Child (13 - 17) ? 'selected="selected" : ''; ?>>Teen (13 - 17)</option>
</select>";
但你真的应该考虑使用ID,所以你不必比较字符串。
答案 2 :(得分:0)
哎呀,那有点乱。您应该阅读PHP's Alternative Syntax。
<?php if ($condition): ?>
This is a test..
<?php endif; ?>