0

有没有办法让这个看起来更有条理?

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."'";
    }
4

3 回答 3

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 的代码,为什么要担心它的外观呢?它确实遵循简单的语法结构(即缩进)。

编辑:更改为仅用大括号括起来的变量,因为我们已经在双引号内。

于 2013-08-23T17:59:05.057 回答
1
 $where = "lvlOne = '{$par1}'";
if (isset( $par2 )) { $where .= " AND lvlTwo = '{$par2}'"; } 
if(isset( $par3 )) { $where .= "AND lvlTwo = '{$par2}' AND lvlThree = '{$par3}'";  }
于 2013-08-23T18:02:29.383 回答
0

在我看来,这会更干净一些。

$where = "lvlOne = '".$par1."'";
if(isset($par2)) {$where .= " AND lvlTwo = '".$par2."'";}
if(isset($par3)) {$where .= " AND lvlThree = '".$par3."'";}
于 2013-08-23T18:00:56.607 回答