Ds \ Vector::reduce()函数是PHP中的内置函数,可通过在回调函数中应用操作将向量减小为单个值。
用法:
mixed public Ds\Vector::reduce( $callback, $initial )
参数:该函数接受上述和以下描述的两个参数:
$callback:该参数具有包含对元素的操作和存储进位的功能。此回调函数包含两个参数,进位和值,其中进位是该函数返回的值,而值是当前迭代中元素的值。
$initial:此参数保存进位的初始值,可以为NULL。
返回值:该函数返回回调函数返回的最终值。
以下示例程序旨在说明PHP中的Ds \ Vector::reduce()函数:
程序1:
// Declare new Vector
$vect = new \Ds\Vector([1, 2, 3, 4, 5]);
echo("Vector Elements\n");
print_r($vect);
// callback function with reduce function
echo("\nElement after performing operation\n");
var_dump($vect->reduce(function($carry, $element) {
return $carry + $element + 2;
}));
?>
输出:
Vector Elements
Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Element after performing operation
int(25)
程序2:
// Declare new Vector
$vect = new \Ds\Vector([10, 20, 30, 40, 50]);
echo("Original vector elements\n");
print_r($vect);
$func_gfg = function($carry, $element) {
return $carry * $element;
};
echo("\nVector after reducing to single element\n");
// Use reduce() function
var_dump($vect->reduce($func_gfg, 10));
?>
输出:
Original vector elements
Ds\Vector Object
(
[0] => 10
[1] => 20
[2] => 30
[3] => 40
[4] => 50
)
Vector after reducing to single element
int(120000000)