如何生成使用分隔列&值的阵列的查询
我有这样的阵列:如何生成使用分隔列&值的阵列的查询
$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
表并用的apex
或dalton
一个paint
价值和black
一个color
值返回所有行,blue
,或red
。
所需的输出是一个MySQL查询,将只返回这些行:
id name color paint
2 p2 red dalton
4 p4 blue apex
如果您需要构建一个这样的查询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
这里我们使用explode
,foreach
和array_values
以达到所需的输出。
<?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
)
)
你能告诉我怎样才能执行的SQL操作。 –
@abilasher你可以分享查询..你想创建.. –
@abilasher你可以尝试这一个.. https://eval.in/788364在我给了最后的SQL查询或我已经改变它AND颜色和油漆之间的条件。 –
你可以请运行这与给定的表结构和条目。 –
@abilasher我检查了[你的问题](https://stackoverflow.com/questions/44602309/making-a-proper-image-capture-of-screen-using-jquery),但不幸的是,不能帮助你用它.. –
好的朋友。 ... –