很抱歉可能会提出一个基本问题,但我正在停电。
如果我有一个数组数组:
Array
(
[appsversion] => Array
(
[0] => appsversion='6.1.0.33'
[1] => appsversion='6.1.0.40'
),
[osversion] => Array
(
[0] => osversion='6.1.0.53'
[1] => osversion='6.1.0.42'
)
)
如何构建一个包含 OR 和 AND 的SQL条件?
即。对于类似的事情:
$condition = '';
foreach ($CONDITIONS as $key => $value) {
# XXX I'm so lost here XXX
}
$sql = sprintf('select %s from mytable where %s', $condition);
$sth = $pg->prepare($sql);
$sth->execute();
我需要构造的字符串
(appsversion='6.1.0.33' OR appsversion='6.1.0.40') AND
(osversion='6.1.0.53' OR osversion='6.1.0.42')
或:
appsversion in ('6.1.0.33', '6.1.0.40') AND
osversion in ('6.1.0.53', '6.1.0.42')
请给我一些提示 - 让我的大脑重新开始: - )
答案 0 :(得分:2)
有:
$where = array();
foreach ($conditions as $values) {
$where[] = '('.implode(' OR ', $values).')';
}
$string = implode(' AND ', $where);
收率:
(appsversion='6.1.0.33' OR appsversion='6.1.0.40') AND (osversion='6.1.0.53' OR osversion='6.1.0.42')
答案 1 :(得分:1)
你的意思是这样的吗?
$condition = "(appsversion = '" . implode("' OR appsversion = '", $conditions['appsversion']) . "')";
$condition .= " AND (osversion = '" . implode("' OR osversion = '", $conditions['osversion']) . "')";
或者,用IN清洁:
$condition = "appsversion IN ('" . implode("', '", $conditions['appsversion']) . "')";
$condition .= " AND osversion IN ('" . implode("', '", $conditions['osversion']) . "')";
答案 2 :(得分:1)
如果您的原始数组没有复制键名并提供“按原样”的值(我在某种程度上误读了您的问题,但可能它很有用):
$conditions = array(
'appsversion' => Array('6.1.0.33', '6.1.0.40'),
'osversion' => Array('6.1.0.53', '6.1.0.42'),
);
foreach ($conditions as $key => &$values) {
foreach($values as &$value)
$value = sprintf("%s='%s'", $key, $value);
$values = sprintf("(%s)", implode(' OR ', $values));
}
unset($values, $value);
echo implode(" AND \n", $conditions);
输出/ Demo:
(appsversion ='6.1.0.33'ODsversion ='6.1.0.40')AND (osversion ='6.1.0.53'OR osversion ='6.1.0.42')
答案 3 :(得分:0)
$conditions1 = array();
foreach ($CONDITIONS['appsversion'] as $value) {
$conditions1[] = sprintf("appversion = '%s'", mysql_real_escape_string($value));
}
$conditions2 = array();
foreach ($CONDITIONS['osversion'] as $value) {
$conditions1[] = sprintf("osversion = '%s'", mysql_real_escape_string($value));
}
$sql = sprintf('select %s from mytable where (%s) AND (%s)', $cols, implode(' OR ', $conditions1), implode(' OR ', $conditions2));
$sth = $pg->prepare($sql);
$sth->execute();
答案 4 :(得分:0)
foreach($C as $key => $value)
{
$str .= ($str ? ' AND ' : '') . '(' . implode(' OR ',$value) . ')';
}