2010-08-01 22 views
0

我正在创建一个自定义搜索表单,当我尝试对结果进行排序时,我得到的是显示的所有对象而不是匹配的条件。我发现的原因是,表单中的一些输入没有默认值,并且在稍后的条件语句中未声明时(仅用于排序),它只显示所有对象,是否满足其他要求或不。我尝试应用一个OR语句,其中特定的变量可以为空,但它给出了相同的结果。像这样 -PHP:有可能的空变量的条件语句

<?php if ($bedrooms >= $min_rooms 
      && $bedrooms <= $max_rooms 
      && $space >= $min_space 
      && $space <= $max_space 
      && $price >= $min_price 
      && $price <= $max_price 
      && $sel_type == $type 
      || $sel_type == '' 
      && $country == $sel_country 
      || $sel_country == '') { ?> 

(见最后两个语句) 我想包括前检查在条件语句中每个变量,但它的感觉就像不必要的代码。你会怎么做?

+0

你不有一个数据库? – 2010-08-01 15:43:23

+0

自定义帖子类型。我认为只需将$ _POST的值发送到结果页面就更简单了。 – 2010-08-01 15:46:45

回答

3

&&操作符比||操作的优先级高,所以目前你的表达进行分组这样的,可能不是你想要的东西:

($bedrooms >= $min_rooms && $bedrooms <= $max_rooms && $space >= $min_space && $space <= $max_space && $price >= $min_price && $price <= $max_price && $sel_type == $type) 
|| 
($sel_type == '' && $country == $sel_country) 
|| 
($sel_country == '') 

尝试添加括号这样实现正确的分组:

($bedrooms >= $min_rooms && $bedrooms <= $max_rooms && $space >= $min_space && $space <= $max_space && $price >= $min_price && $price <= $max_price && ($sel_type == $type || $sel_type == '') && ($country == $sel_country || $sel_country == '')) 
+0

啊,谢谢!为什么我不试试... – 2010-08-01 15:52:54

1

由于&&操作员比||操作具有更高的precedence,您的表达可能会失败。这意味着像这样的表达式:

… && $sel_type == $type || $sel_type == '' 

等效于此(通过使用括号强调运算符优先级):

(… && $sel_type == $type) || $sel_type == '' 

要修复把||表达式括号中:

$bedrooms >= $min_rooms && $bedrooms <= $max_rooms && $space >= $min_space && $space <= $max_space && $price >= $min_price && $price <= $max_price && ($sel_type == $type || $sel_type == '') && ($country == $sel_country || $sel_country == '') 

此外,如果您使用between函数等辅助函数,则表达式可能更易于阅读和维护:

function between($val, $min, $max) { 
    return $min <= $val && $val <= $max; 
} 

那么你的表情写着:

between($bedrooms, $min_rooms, $max_rooms) && between($space, $min_space, $max_space) && between($price, $min_price, $max_price) && ($sel_type == $type || $sel_type == '') && ($country == $sel_country || $sel_country == '') 
+0

伟大的技巧,谢谢! – 2010-08-04 15:20:05