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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
