Php 如何使用分隔列数组生成查询&;价值观
我有这个阵列:Php 如何使用分隔列数组生成查询&;价值观,php,mysql,arrays,select,where-in,Php,Mysql,Arrays,Select,Where In,我有这个阵列: $filter=['color*black','color*blue','color*red','paint*apex','paint*dalton']; $filter中的每个值都有两个子字符串,由*分隔。第一个子字符串表示数据库表列,第二个子字符串表示该列所需的值 我的产品表如下所示: id name color paint 1 p1 black compo 2 p2 red dalton 3
$filter=['color*black','color*blue','color*red','paint*apex','paint*dalton'];
$filter
中的每个值都有两个子字符串,由*
分隔。第一个子字符串表示数据库表列,第二个子字符串表示该列所需的值
我的产品
表如下所示:
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
表,并返回paint
值为apex
或dalton
且color
值为black
、blue
或red
的所有行
所需的输出是一个mysql查询,它将只返回以下行:
id name color paint
2 p2 red dalton
4 p4 blue apex
这里我们使用
explode
、foreach
和array\u值来实现所需的输出
如果您需要构建一个类似于以下内容的查询SELECT*从产品中(颜色为('black','blue','red'))和(油漆为('apex','dalton'))
,那么下面的代码可能会很有用(请检查):
对给定的表数据结构运行此查询:
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
您能告诉我如何执行sql操作吗?您可以试试这个。。在我给出的上一个SQL查询中,或者我已将其更改为“颜色和油漆之间的条件”。请使用给定的表结构和条目运行该查询。@abilasher我已检查,但很遗憾,无法帮助您执行该查询。。
$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