2010-08-01 55 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