다음 코드가 있습니다.
function lower_than_10($i) {
return ($i < 10); }
다음과 같이 어레이를 필터링할 수 있습니다.
$arr = array(7, 8, 9, 10, 11, 12, 13); $new_arr = array_filter($arr, 'lower_than_10');
lower_than_10에 인수를 추가하여 체크할 숫자도 받아들이려면 어떻게 해야 합니까?예를 들어, 만약 내가 이걸 가지고 있다면:
function lower_than($i, $num) {
return ($i < $num); }
10에서 $num으로 전달되는 array_filter에서 호출하려면 어떻게 해야 합니까?
질문에 대한 답변
php 5.3 이상을 사용하는 경우 closure를 사용하여 코드를 단순화할 수 있습니다.
$NUM = 5; $items = array(1, 4, 5, 8, 0, 6); $filteredItems = array_filter($items, function($elem) use($NUM){
return $elem < $NUM; });
클로저를 사용하는 @Charles 솔루션의 대안으로 문서 페이지의 코멘트에서 실제로 예를 찾을 수 있습니다.목적의 상태()$num
와 콜백 방식(인수로 사용)을 가지는 오브젝트를 작성하는 것이 목적입니다.
class LowerThanFilter {
private $num;
function __construct($num) {
$this->num = $num;
}
function isLower($i) {
return $i < $this->num;
} }
사용방법(데모):
$arr = array(7, 8, 9, 10, 11, 12, 13); $matches = array_filter($arr, array(new LowerThanFilter(12), 'isLower')); print_r($matches);
사이드노트로, 다음과 같이 치환할 수 있습니다.LowerThanFilter
보다 일반적인 것으로서NumericComparisonFilter
같은 방법으로isLower
,isGreater
,isEqual
기타. 생각만 하고 데모도 하고…
PHP 5.3 이상에서는 클로저를 사용할 수 있습니다.
function create_lower_than($number = 10) { // The "use" here binds $number to the function at declare time. // This means that whenever $number appears inside the anonymous // function, it will have the value it had when the anonymous // function was declared.
return function($test) use($number) { return $test < $number; }; }
// We created this with a ten by default.
Let's test. $lt_10 = create_lower_than(); var_dump($lt_10(9)); // True var_dump($lt_10(10)); // False var_dump($lt_10(11)); // False
// Let's try a specific value. $lt_15 = create_lower_than(15); var_dump($lt_15(13)); // True var_dump($lt_15(14)); // True var_dump($lt_15(15)); // False var_dump($lt_15(16)); // False
// The creation of the less-than-15 hasn't disrupted our less-than-10: var_dump($lt_10(9)); // Still true var_dump($lt_10(10)); // Still false var_dump($lt_10(11)); // Still false
// We can simply pass the anonymous function anywhere that a // 'callback' PHP type is expected, such as in array_filter: $arr = array(7, 8, 9, 10, 11, 12, 13); $new_arr = array_filter($arr, $lt_10); print_r($new_arr);
여러 파라미터를 함수에 전달해야 할 경우 “,”: 를 사용하여 사용 설명서에 추가할 수 있습니다.
$r = array_filter($anArray, function($anElement) use ($a, $b, $c){
//function body where you may use $anElement, $a, $b and $c });
옌스그램 답변의 연장선상에서 마법의 방법을 사용하여 마법을 추가할 수 있습니다.
class LowerThanFilter {
private $num;
public function __construct($num) {
$this->num = $num;
}
public function isLower($i) {
return $i < $this->num;
}
function __invoke($i) {
return $this->isLower($i);
} }
이것으로 할 수 있습니다.
$arr = array(7, 8, 9, 10, 11, 12, 13); $matches = array_filter($arr, new LowerThanFilter(12)); print_r($matches);