我有这个数组:
$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
表并返回paint
值apex
或dalton
和{{1}的所有行} color
,black
或blue
的值。
所需的输出是一个只返回这些行的mysql查询:
red
答案 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)
我们正在使用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
)
)