PHP - Ds Map::reduce() 函式



PHP 的 Ds\Map::reduce() 函式用於透過將回調函式應用於當前對映的每個元素來將對映簡化為單個值。

回撥函式的返回值成為下一個元素的新累加值,並且在處理完所有元素後,reduce() 函式返回最終的累加值。

語法

以下是 PHP Ds\Map::reduce() 函式的語法:

public Ds\Map::reduce(callable $callback, mixed $initial = ?): mixed

引數

以下是此函式的引數:

  • callback − 此引數包含一個對集合元素進行操作的函式。
  • initial − 累加值的初始值,可以為 null

以下是 callback 函式的語法:

callback(mixed $carry, mixed $key, mixed $value): mixed

返回值

此函式返回最終回撥函式的值。

示例 1

以下是 PHP Ds\Map::reduce() 函式的基本示例:

<?php  
   $map = new \Ds\Map([1, 2, 3, 4, 5]);  
   echo("The map elements: \n");  
   print_r($map);  
   echo("\nAn element after performing operation: \n");  
   var_dump($map->reduce(function($carry, $key, $element) {  
      return $carry + $element + 2; 
   }));
?>

輸出

上述程式產生以下輸出:

The map elements:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 0
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => 2
            [value] => 3
        )

    [3] => Ds\Pair Object
        (
            [key] => 3
            [value] => 4
        )

    [4] => Ds\Pair Object
        (
            [key] => 4
            [value] => 5
        )

)

An element after performing operation:
int(25)

示例 2

以下是 PHP Ds\Map::reduce() 函式的另一個示例。我們使用此函式透過回撥函式將此對映 ([10, 20, 30, 40, 50]) 簡化為單個值。

<?php  
   $map = new \Ds\Map([10, 20, 30, 40, 50]);  
   echo("The original map elements: \n");  
   print_r($map);  
   $func = function($carry, $key, $element) {  
      return $carry * $element;  
   };  
   echo("\nThe map after reducing to single element: \n");  
   var_dump($map->reduce($func, 10));
?>

輸出

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

The original map elements:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 0
            [value] => 10
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => 20
        )

    [2] => Ds\Pair Object
        (
            [key] => 2
            [value] => 30
        )

    [3] => Ds\Pair Object
        (
            [key] => 3
            [value] => 40
        )

    [4] => Ds\Pair Object
        (
            [key] => 4
            [value] => 50
        )

)

The map after reducing to single element:
int(120000000)
php_function_reference.htm
廣告