인수가 있는 PHP array_filter
다음 코드가 있습니다.
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);
PHP 7.4 화살표 기능을 사용할 수 있기 때문에 더욱 깔끔하게 할 수 있습니다.
$max = 10;
$arr = array(7, 8, 9, 10, 11, 12, 13);
$new_arr = array_filter($arr, fn ($n) => $n < $max);
class ArraySearcher{
const OPERATOR_EQUALS = '==';
const OPERATOR_GREATERTHAN = '>';
const OPERATOR_LOWERTHAN = '<';
const OPERATOR_NOT = '!=';
private $_field;
private $_operation;
private $_val;
public function __construct($field,$operation,$num) {
$this->_field = $field;
$this->_operation = $operation;
$this->_val = $num;
}
function __invoke($i) {
switch($this->_operation){
case '==':
return $i[$this->_field] == $this->_val;
break;
case '>':
return $i[$this->_field] > $this->_val;
break;
case '<':
return $i[$this->_field] < $this->_val;
break;
case '!=':
return $i[$this->_field] != $this->_val;
break;
}
}
}
이를 통해 다차원 배열의 항목을 필터링할 수 있습니다.
$users = array();
$users[] = array('email' => 'user1@email.com','name' => 'Robert');
$users[] = array('email' => 'user2@email.com','name' => 'Carl');
$users[] = array('email' => 'user3@email.com','name' => 'Robert');
//Print all users called 'Robert'
print_r( array_filter($users, new ArraySearcher('name',ArraySearcher::OPERATOR_EQUALS,'Robert')) );
언급URL : https://stackoverflow.com/questions/5482989/php-array-filter-with-arguments
'source' 카테고리의 다른 글
| "java - cp"와 "java - jar"의 차이점은 무엇입니까? (0) | 2022.12.03 |
|---|---|
| php / mariadb 업데이트 후 데이터 로컬 파일 로드 금지 (0) | 2022.12.03 |
| PHP - 컬 디버깅 (0) | 2022.12.03 |
| 라라벨 웅변 모델의 세 테이블 결합 방법 (0) | 2022.12.03 |
| 데이터베이스에서 상태 열의 내용을 제목으로 표시하는 방법 (0) | 2022.12.03 |