I have this array:
$filter=['color*black','color*blue','color*red','paint*apex','paint*dalton'];
Each value in $filter
has two substrings separated by *
. The first substring represents a database table column and the second represents a desired value for that column.
My products
table looks like this:
id name color paint
1 p1 black compo
2 p2 red dalton
3 p3 pink apex
4 p4 blue apex
5 p5 cream compo
Using $filter
, I need to search the products
table and return all rows with a paint
value of apex
or dalton
AND a color
value of black
, blue
, or red
.
The desired output is a mysql query that will only return these rows:
id name color paint
2 p2 red dalton
4 p4 blue apex
If You need to construct a query like this SELECT * FROM products WHERE (color IN ('black', 'blue', 'red')) AND (paint IN ('apex', 'dalton'))
, then the code below might be useful (please, check it 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);
Running this query against the given table data structure:
id name color paint
1 p1 black compo
2 p2 red dalton
3 p3 pink apex
4 p4 blue apex
5 p5 cream compo
will match the following rows:
2 p2 red dalton
4 p4 blue apex
Here we are using explode
, foreach
and array_values
to achieve desired output.
<?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);
Output:
Array
(
[before] => Array
(
[0] => color
[1] => paint
)
[after] => Array
(
[0] => black
[1] => blue
[2] => red
[3] => apex
[4] => dalton
)
)