Ds \ Map::reduce()函數是PHP中的一個內置函數,用於通過使用回調函數應用操作將映射減少為單個值。
用法:
mixed public Ds\Map::reduce( $callback, $initial )
參數:該函數接受上述和以下描述的兩個參數:
- $callback:該參數具有包含對元素的操作和存儲進位的函數。此回調函數包含以下列出的三個參數:
- carry:它保存前一個回調的返回值,如果是第一次迭代,則返回初始值。
- key:它掌握了當前迭代的關鍵。
- value:它保存當前迭代的值。
- $initial:此參數保存進位的初始值,可以為NULL。
返回值:該函數返回回調函數返回的最終值。
以下示例程序旨在說明PHP中的Ds \ Map::reduce()函數:
程序1:
<?php
// Declare a new map
$map = new \Ds\Map(["a" => 1, "b" => 3, "c" => 5]);
echo("Map Elements\n");
print_r($map);
// Callback function with reduce function
echo("\nElement after performing operation\n");
var_dump($map->reduce(function($carry, $key, $element) {
return $carry + $element + 2;
}));
?>
輸出:
Map Elements Ds\Map Object ( [0] => Ds\Pair Object ( [key] => a [value] => 1 ) [1] => Ds\Pair Object ( [key] => b [value] => 3 ) [2] => Ds\Pair Object ( [key] => c [value] => 5 ) ) Element after performing operation int(15)
程序2:
<?php
// Declare new Map elements
$map = new \Ds\Map(["a" => 10, "b" => 20,
"c" => 30, "d" => 40, "e" => 50]);
echo("Original map elements\n");
print_r($map);
$func_gfg = function($carry, $key, $element) {
return $carry * $element;
};
echo("\nMap after reducing to single element\n");
// Use reduce() function
var_dump($map->reduce($func_gfg, 10));
?>
輸出:
Original map elements Ds\Map Object ( [0] => Ds\Pair Object ( [key] => a [value] => 10 ) [1] => Ds\Pair Object ( [key] => b [value] => 20 ) [2] => Ds\Pair Object ( [key] => c [value] => 30 ) [3] => Ds\Pair Object ( [key] => d [value] => 40 ) [4] => Ds\Pair Object ( [key] => e [value] => 50 ) ) Map after reducing to single element int(120000000)
參考: https://www.php.net/manual/en/ds-map.reduce.php
相關用法
- PHP Ds\Set reduce()用法及代碼示例
- PHP Ds\Deque reduce()用法及代碼示例
- PHP Ds\Sequence reduce()用法及代碼示例
- PHP Ds\Vector reduce()用法及代碼示例
- Javascript Array reduce()用法及代碼示例
- PHP max( )用法及代碼示例
- PHP key()用法及代碼示例
- CSS var()用法及代碼示例
- PHP each()用法及代碼示例
注:本文由純淨天空篩選整理自R_Raj大神的英文原創作品 PHP | Ds\Map reduce() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。