我试图找到最合乎逻辑(一如既往)的方式来接受查询中的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()不会在我的循环中起作用。谢谢你的帮助。
答案 0 :(得分:2)
它应该像插入参数数组一样容易,例如 -
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
}
}