有没有办法让这个看起来更有条理?
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."'";
}
答案 0 :(得分: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值得代码,为什么要担心它看起来像什么?它确实遵循简单的语法结构(即缩进)。
编辑:更改为用大括号括起变量,因为我们已经在双引号内。
答案 1 :(得分:1)
$where = "lvlOne = '{$par1}'";
if (isset( $par2 )) { $where .= " AND lvlTwo = '{$par2}'"; }
if(isset( $par3 )) { $where .= "AND lvlTwo = '{$par2}' AND lvlThree = '{$par3}'"; }
答案 2 :(得分:0)
在我看来,这会更加清晰。
$where = "lvlOne = '".$par1."'";
if(isset($par2)) {$where .= " AND lvlTwo = '".$par2."'";}
if(isset($par3)) {$where .= " AND lvlThree = '".$par3."'";}