2011-09-29 41 views
0

对不起,可能会提出一个基本问题,但我正在停电。从数组阵列中制作一个字符串

如果我有一个数组的数组:

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和它一个SQL条件?

I.e.这样的事情:

$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') 

请给我一些提示 - 让我的大脑又开始了:-)

回答

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') 
+0

真棒,谢谢大家的答案 –

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']) . "')"; 
+0

谢谢,但如果我不知道是什么键? (即不知道有“appsversion”和“osversion”)。 –

+0

这会产生'appsversion =('6.1.0.33'或'6.1.0.40')'。我不认为这会正常工作。 – Czechnology

+0

发布后我发现我的错误,更新,谢谢。 @Alex然后你拧了。你为什么不知道钥匙? – CodeCaster

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(); 
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' OR appsversion = '6.1.0.40')AND (OSVERSION = '6.1.0.53' OR OSVERSION = '6.1.0.42')

0
foreach($C as $key => $value) 
{ 
    $str .= ($str ? ' AND ' : '') . '(' . implode(' OR ',$value) . ')'; 
} 
相关问题