array_reduce() Function
PHP的这个内建函数用于将数组元素简化为一个值,该值可以是浮点数、整数或字符串值。该函数使用用户定义的回调函数来减少输入数组。
语法
1 | array_reduce($array, own_function, $initial) |
参数:该函数接受三个参数,描述如下:
- $array (mandatory):这是一个推荐参数,指的是需要减少的原始数组。
- own_function (mandatory):这个参数是als mandatory,指的是用于保存$数组值的用户定义函数
- $initial(可选):这个参数是可选的,它引用要发送给函数的值。
返回值:这个函数返回经过简化的结果。它可以是任何类型的int、float或string。
例子
1 2 3 4 5 6 7 8 9 10 11 | Input : $array = (15, 120, 45, 78) $initial = 25 own_function() takes two parameters and concatenates them with "and" as a separator in between Output : 25 and 15 and 120 and 45 and 78 Input : $array = array(2, 4, 5); $initial = 1 own_function() takes two parameters and multiplies them. Output : 40 |
在这个程序中,我们将看到一个整数元素数组如何被简化为一个字符串值。我们还通过了我们选择的第一个元素。
1 2 3 4 5 6 7 8 9 10 | <?php // PHP function to illustrate the use of array_reduce() function own_function($element1, $element2) { return $element1 . " and " . $element2; } $array = array(15, 120, 45, 78); print_r(array_reduce($array, "own_function", "Initial")); ?> |
输出
1 | Initial and 15 and 120 and 45 and 78 |
在下面的程序中,array_reduce使用own_function()将给定数组还原为数组中所有元素的乘积。
1 2 3 4 5 6 7 8 9 10 11 | <?php // PHP function to illustrate the use of array_reduce() function own_function($element1, $element2) { $element1 = $element1 * $element2; return $element1; } $array = array(2, 4, 5, 10, 100); print_r(array_reduce($array, "own_function", "2")); ?> |
输出
1 | 80000 |
参考
http://php.net/manual/en/function.array-reduce.php