PHP - Ds Set filter() 函式



PHP 的 Ds\Set::filter() 函式用於透過可呼叫物件來建立一個新的集合,該可呼叫物件決定了哪些值應該包含在新建立的集合中。

可呼叫函式是一個可選引數,它對於應該包含在集合中的值返回 true,對於不應該包含的值返回 false

語法

以下是 PHP Ds\Set::filter() 函式的語法:

public Ds\Set::filter(callable $callback = ?): Ds\Set

引數

此函式接受一個名為“回撥”函式的單個引數,如下所述:

  • callback − 一個可選的回撥函式,如果值應該包含則返回 true;否則返回 'false'。

以下是可呼叫函式的語法:

callback(mixed $value): bool

返回值

此函式返回一個新集合,其中包含所有回撥函式返回 true 的值,或者如果沒有提供回撥函式則包含所有轉換為 true 的值。

示例 1

以下是 PHP Ds\Set::filter() 函式的基本示例。

<?php
   $set = new \Ds\Set([1,2,3,4,5,6,7,8,9]);
   echo "The original set elements: \n";
   print_r($set);
   echo "The elements after the filter() function is invoked : \n";
   print_r($set->filter(function($value) {
      return ($value+3)%2 == 0;
   }));
?>

輸出

以上程式產生以下輸出:

The original set elements:
Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)
The elements after the filter() function is invoked :
Ds\Set Object
(
    [0] => 1
    [1] => 3
    [2] => 5
    [3] => 7
    [4] => 9
)

示例 2

以下是 PHP Ds\Set::filter() 函式的另一個示例。我們使用此函式使用一個可呼叫函式建立一個新集合,該函式返回 11 的倍數的值。

<?php
   $set = new \Ds\Set([74, 99, 177, 66, 198, 121, 154]);
   echo "The original set elements: \n";
   print_r($set);
   echo "The elements which are divisbile by 11 are: \n";
   print_r($set->filter(function($value) {
      return $value%11 == 0;
   }));
?>

輸出

執行上述程式後,將產生以下輸出:

The original set elements:
Ds\Set Object
(
    [0] => 74
    [1] => 99
    [2] => 177
    [3] => 66
    [4] => 198
    [5] => 121
    [6] => 154
)
The elements which are divisbile by 11 are:
Ds\Set Object
(
    [0] => 99
    [1] => 66
    [2] => 198
    [3] => 121
    [4] => 154
)

示例 3

在下面的示例中,我們使用 PHP Ds\Set::filter() 函式建立一個新集合,其中僅包含小於 50 的值。回撥函式對於當前集合 ([1, 5, 10, 15, 20]) 中的值返回 true,其中與 3 的乘積小於 50。

<?php
   $set = new \Ds\Set([1, 5, 10, 15, 20]);
   echo "The original set elements: \n";
   print_r($set);
   echo "The elements after applying the filter() function are: \n";
   print_r($set->filter(function($value) {
      return $value*3<50;
   }));
?>

輸出

執行上述程式後,將生成以下輸出:

The original set elements:
Ds\Set Object
(
    [0] => 1
    [1] => 5
    [2] => 10
    [3] => 15
    [4] => 20
)
The elements after applying the filter() function are:
Ds\Set Object
(
    [0] => 1
    [1] => 5
    [2] => 10
    [3] => 15
)

示例 4

如果可呼叫函式對於當前集合的每個值都返回 'false',則新建立的集合中將不包含任何值。

<?php
   $set = new \Ds\Set([1, 5, 10, 15, 20]);
   echo "The original set elements: \n";
   print_r($set);
   echo "The elements after applying the filter() function are: \n";
   print_r($set->filter(function($value) {
      return $value+($value+1) == 42;
   }));
?>

輸出

執行上述程式後,將顯示以下輸出:

The original set elements:
Ds\Set Object
(
    [0] => 1
    [1] => 5
    [2] => 10
    [3] => 15
    [4] => 20
)
The elements after applying the filter() function are:
Ds\Set Object
(
)
php_function_reference.htm
廣告