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

How to generate a query using an array of delimited columns & values

我有这个数组:

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

$filter 中的每个值都有两个由 * 分隔的子字符串。第一个子字符串表示数据库 table 列,第二个子字符串表示该列的所需值。

我的 products table 看起来像这样:

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 table 和 return 所有 paint 值为 apex 的行或daltoncolorblackbluered

所需的输出是一个 mysql 查询,它只会 return 这些行:

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

此处我们使用 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
        )
)

如果您需要构建这样的查询 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);

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

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