1 回答
TA贡献1770条经验 获得超3个赞
我已经使用闭包实现了这一点,有一组数组定义了用于过滤器类型和运算符的回调函数。
每次应用过滤器时,它首先检查过滤器是否正常,然后array_filter()与查找表中的相应回调一起使用,根据被过滤的值检查每个项目。一旦过滤了整个数字列表,它就会计算出如何将这些结果与之前的结果结合起来。再次回调知道这部分的逻辑......
// the content which was scraped
$scrapedResults = [1, 10, 11, 1216, 15, 55, 556, 123, 225, -15,];
// the user created filters
$filters = [
['filter' => ['more' => 0], 'operator' => null,],
['filter' => ['less' => 15], 'operator' => 'and'],
['filter' => ['equal' => 1216], 'operator' => 'or'],
];
// Implementation of the filters
$filterType = ['more' => function ($a, $b) { return $a > $b; },
'less' => function ($a, $b) { return $a < $b; },
'equal' => function ($a, $b) { return $a == $b; }];
// Implementation of the operators
$operators = ['and' => function ($old, $result ) {
return array_intersect($old, $result);
},
'or' => function ($old, $result ) {
return array_merge($old, $result);
}];
$output = [];
foreach ( $filters as $filter ) {
$currentType = array_keys($filter['filter'])[0];
if ( !isset($filterType[$currentType]) ) {
throw new InvalidArgumentException('unknown action given');
}
$filterValue = $filter['filter'][$currentType];
$callback = $filterType[$currentType];
$filterRes = array_filter($scrapedResults, function ($a)
use ($callback, $filterValue) {
return $callback($a, $filterValue);
});
if ( $filter['operator'] == null ) {
$output = $filterRes;
}
else if ( isset($operators[$filter['operator']]) ) {
$output = $operators[$filter['operator']]($output, $filterRes);
}
}
echo "output->";
print_r($output);
这输出...
output->Array
(
[0] => 1
[1] => 10
[2] => 11
[3] => 1216
)
- 1 回答
- 0 关注
- 123 浏览
添加回答
举报