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 關注
- 146 瀏覽
添加回答
舉報