美好的一天,
我有一个数组(请求);
$appliedFilters = [
"6",
"37",
"40",
"41"
]
然后我将所有产品按“过滤器类别”分组(我知道这是json输出,但更易于共享);
{
"6":[
{
"product_id":"12",
}
],
"7":[
{
"product_id":"12",
}
],
"12":[],
"48":[
{
"product_id":"12",
}
],
"33":[],
"34":[],
"35":[],
"36":[
{
"product_id":"12",
}
],
"37":[
{
"product_id":"12",
}
],
"38":[],
"39":[],
"40":[],
"41":[]
}
如何退回所有$ appliedFilters与过滤器完全相同的产品?
我只需要$ appliedFilters与filterCategories完全相同的产品。
例如,给定的$appliedFilters
应该返回 0个产品,因为不存在带有过滤器40或41的产品。
第二个示例
$appliedFilters = [
"6",
"36",
"48"
]
在这种情况下,应该返回product_id = 12的产品,因为所有$appliedFilters
都有该产品。该产品是否还具有更多的过滤器(例如7和48)也没关系。
到目前为止,我已经尝试过,但是预期结果不正确:
// fetch all filter items
$productsGroupByFilterItems = [];
$rows = $this->getFilters();
foreach ($rows as $row) {
$productsGroupByFilterItems[$row['filterItem_id']] = [];
}
// group all products by filter ids
foreach ($products as $product) {
$productFilters = explode(',', $product['chosenFilterIds']);
foreach ($productsGroupByFilterItems as $filterItemId => $filterItem) {
foreach ($productFilters as $filterId) {
if ($filterId == $filterItemId) {
$productsGroupByFilterItems[$filterItemId][] = $product;
}
}
}
}
// remove all products that are not part of the applied filters
foreach($productsGroupByFilterItems as $key => $val)
{
if(array_search($key, $appliedFilters) === false)
{
unset($productsGroupByFilterItems[$key]);
}
}
// finally return only the products that exist in all the filters items
return call_user_func_array('array_intersect_key', $productsGroupByFilterItems);
答案 0 :(得分:0)
代码太复杂,无法解析,但这可能会让您有所了解。
假设产品以$products
形式存在于PHP数组中,只需翻转$appliedFilters
即可创建密钥,然后计算密钥的交集:
$result = array_intersect_key(array_flip($appliedFilters), $products);
这将为您提供$products
中密钥在$appliedFilters
中的所有项目。相反,请查看array_diff_key。
答案 1 :(得分:0)
您应该执行以下操作(我已将JSON转换为简单数组)。
$filteredData = [
6 => [
['product_id' => 12]
],
7 => [
['product_id' => 12]
],
12 => [],
48 => [
['product_id' => 12]
],
33 => [],
34 => [],
35 => [],
36 => [
['product_id' => 12]
],
37 => [
['product_id' => 12]
],
38 => [],
39 => [],
40 => [],
41 => []
];
//case 1
$appliedFilters = [
"6",
"37",
"40",
"41"
];
$out = array_intersect_key($filteredData, array_flip($appliedFilters));
$products = null;
foreach ($out as $filteredProducts) {
if ($products === null) {
$products = $filteredProducts;
continue;
}
$products = @array_intersect($products, $filteredProducts);
}
var_dump($products);
//case 1
$appliedFilters = [
"6",
"36",
"48"
];
$out = array_intersect_key($filteredData, array_flip($appliedFilters));
$products = null;
foreach ($out as $filteredProducts) {
if ($products === null) {
$products = $filteredProducts;
continue;
}
$products = @array_intersect($products, $filteredProducts);
}
var_dump($products);
结果是:
//case 1
array(0) {
}
//case 2
array(1) {
[0]=>
array(1) {
["product_id"]=>
int(12)
}
}
您可以在此处查看它的运行情况:https://3v4l.org/JEjcB
基本上,我们将已过滤数组的键和过滤键相交。然后将所有乘积数组相交成一个循环。