php
  • syntax
  • switch-statement
  • 2013-08-23 71 views 0 likes 
    0

    有沒有辦法讓這個看起來更有條理?PHP切換多個參數

    if (!isset($par2) && !isset($par3)) { 
         $where = "lvlOne = '".$par1."'"; 
    
        } elseif(isset($par2) && !isset($par3)) { 
         $where = "lvlOne = '".$par1."' AND lvlTwo = '".$par2."'"; 
    
        } elseif(isset($par2) && isset($par3)) { 
         $where = "lvlOne = '".$par1."' AND lvlTwo = '".$par2."' AND lvlThree = '".$par3."'"; 
        } 
    
    +2

    您可以將多個參數傳遞給isset()函數 –

    +2

    你看上去構造查詢。爲什麼不準備這個? –

    +1

    當然。一些塑料箱,塗料,一點粉塵,我們會立刻看到它像新的一樣。 –

    回答

    3

    級聯:

    $where = "lvlOne = '{$par1}'"; 
    
    if(isset($par2)) { 
        $where .= " AND lvlTwo = '{$par2}'"; 
    } 
    
    if(isset($par3)) { 
        $where .= " AND lvlThree = '{$par3}'"; 
    } 
    

    級聯三元:

    $where = "lvlOne = '{$par1}'"; 
    $where .= isset($par2)?" AND lvlTwo = '{$par2}'":''; 
    $where .= isset($par3)?" AND lvlThree = '{$par3}'":''; 
    

    破滅與陣列:

    //where this one is nice is that regardless of the number of parameters, 
    //you always end up with the proper 'AND' between each where clause. 
    $where = array("lvlOne = '{$par1}'"); 
    if(isset($par2)){ 
        $where[] = "lvlTwo = '{$par2}'" 
    } 
    if(isset($par3)){ 
        $where[] = "lvlThree = '{$par3}'" 
    } 
    $where = impode(' AND ', $where); 
    

    在端雖然,如果它的工作原理,而不是一些神聖的憎惡,每天wtf值得鱈魚e,爲什麼擔心它看起來像什麼?它遵循一個簡單的語法結構(即縮進)。

    編輯:更改爲只包含帶花括號的變量,因爲我們已經在雙引號內。

    +0

    好! ,我想看到更多的選擇,但我喜歡這個。 –

    +0

    只是爲了學習!,非常感謝! –

    0

    在我看來,這將是相當清潔。

    $where = "lvlOne = '".$par1."'"; 
    if(isset($par2)) {$where .= " AND lvlTwo = '".$par2."'";} 
    if(isset($par3)) {$where .= " AND lvlThree = '".$par3."'";} 
    
    1
    $where = "lvlOne = '{$par1}'"; 
    if (isset($par2)) { $where .= " AND lvlTwo = '{$par2}'"; } 
    if(isset($par3)) { $where .= "AND lvlTwo = '{$par2}' AND lvlThree = '{$par3}'"; } 
    
    相關問題