2017-05-06 183 views
2

我有这样的阵列:如何生成使用分隔列&值的阵列的查询

$filter=['color*black','color*blue','color*red','paint*apex','paint*dalton']; 

每个值在$filter具有由*分离的两个子串。第一个子字符串表示数据库表格列,第二个表示该列的所需值。

products表看起来像这样:

id name color paint 
1  p1  black  compo 
2  p2  red  dalton 
3  p3  pink  apex 
4  p4  blue  apex 
5  p5  cream  compo 

使用$filter,我需要搜索products表并用的apexdalton一个paint价值和black一个color值返回所有行,blue,或red

所需的输出是一个MySQL查询,将只返回这些行:

id name color paint 
2  p2  red  dalton 
4  p4  blue  apex 

回答

2

如果您需要构建一个这样的查询SELECT * FROM products WHERE (color IN ('black', 'blue', 'red')) AND (paint IN ('apex', 'dalton')),然后下面的代码可能是有用的(请检查here):

$filter = array(
    0 => "color*black", 
    1 => "color*blue", 
    2 => "color*red", 
    3 => "paint*apex", 
    4 => "paint*dalton" 
); 

$elements = []; 

foreach ($filter as $value) { 
    list($before, $after) = explode('*', $value); 
    $elements[$before][] = $after; 
} 

$parts = []; 

foreach ($elements as $column => $values) { 
    $parts[] = "(`$column` IN ('" . implode("', '", $values) . "'))"; 
} 

$query = 'SELECT * FROM `products` WHERE ' . implode(' AND ', $parts); 

运行针对给定的表数据结构此查询:

id name color paint 
1  p1  black  compo 
2  p2  red  dalton 
3  p3  pink  apex 
4  p4  blue  apex 
5  p5  cream  compo 

将匹配以下行:

2  p2  red  dalton 
4  p4  blue  apex 
+0

你可以请运行这与给定的表结构和条目。 –

+0

@abilasher我检查了[你的问题](https://stackoverflow.com/questions/44602309/making-a-proper-image-capture-of-screen-using-jquery),但不幸的是,不能帮助你用它.. –

+0

好的朋友。 ... –

1

这里我们使用explodeforeacharray_values以达到所需的输出。

Try this code snippet here

<?php 

$filter = array(
    0 => "color*black", 
    1 => "color*blue", 
    2 => "color*red", 
    3 => "paint*apex", 
    4 => "paint*dalton"); 

$result=array(); 
foreach($filter as $value) 
{ 
    list($before,$after)=explode("*",$value); 
    $result["before"][$before]=$before; 
    $result["after"][$after]=$after; 
} 
$result["before"]= array_values($result["before"]); 
$result["after"]= array_values($result["after"]); 
print_r($result); 

输出:

Array 
(
    [before] => Array 
     (
      [0] => color 
      [1] => paint 
     ) 
    [after] => Array 
     (
      [0] => black 
      [1] => blue 
      [2] => red 
      [3] => apex 
      [4] => dalton 
     ) 
) 
+0

你能告诉我怎样才能执行的SQL操作。 –

+0

@abilasher你可以分享查询..你想创建.. –

+0

@abilasher你可以尝试这一个.. https://eval.in/788364在我给了最后的SQL查询或我已经改变它AND颜色和油漆之间的条件。 –