我正在尝试找到最合乎逻辑(一如既往)的方式来接受查询中的 WHERE 参数列表。我遇到了如何确定它是否是数组末尾的常见问题,我需要添加或不添加另一个“AND”
$params = array(
array("id","=","1"),
array("id","!=","2"),
array("name","=","test"),
)
someQuery($params);
private function someQuery($where = null){
$this->q = "SELECT stuff FROM table";
if ($where){
$this->q .= " WHERE ";
foreach($where as $x){
$this->q .= implode(" ", $x);
if (!notLastElement) $this->q .= " AND ";
}
}
}
我似乎建议使用 end()、reset()、slice、带计数器的 for 循环等。但似乎没有人同意一个答案。我相信 end() 不会在我的循环中工作。感谢您的帮助。
最佳答案
它应该像内爆参数数组一样简单,例如 -
private function someQuery($where = null){
$this->q = "SELECT stuff FROM table";
if ($where){
$parameters = array();
foreach($where as $x){
$condition = implode(' ', $x); // I'd review this - why are you forming your parameter array the way that you are?
array_push($parameters, $condition);
}
$conditions = implode(' AND ', $parameters);
$this->q .= ' WHERE ' . $conditions; // only concatenate once
}
}
关于php - 附加未知数量的 WHERE 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28415510/