如何使用分隔列数组生成查询&值

时间:2017-05-06 10:39:01

标签: php mysql arrays select where-in

我有这个数组:

$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表并返回paintapexdalton和{{1}的所有行} colorblackblue的值。

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

red

2 个答案:

答案 0 :(得分:2)

如果您需要构建类似String s = "1010a"; try{ int i = Integer.parseInt(s, 2); //Do something(no is valid) }catch(NumberFormatException e){ //Display error(no is invalid) } 的查询,那么下面的代码可能会有用(请检查here):

SELECT * FROM products WHERE (color IN ('black', 'blue', 'red')) AND (paint IN ('apex', 'dalton'))

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

$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

答案 1 :(得分: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
        )
)