对于 some或 other原因,array_reduce
PHP 中的函数只接受整数作为它的第三个参数。这第三个参数用作整个缩减过程的起点:
function int_reduc($return, $extra) {
return $return + $extra;
}
$arr = array(10, 20, 30, 40);
echo array_reduce($arr, 'int_reduc', 0); //Will output 100, which is 0 + 10 + 20 + 30 + 40
function str_reduc($return, $extra) {
return $return .= ', ' . $extra;
}
$arr = array('Two', 'Three', 'Four');
echo array_reduce($arr, 'str_reduc', 'One'); //Will output 0, Two, Three, Four
在第二次调用中,'One'
被转换为它的整数值,即 0,然后被使用。
为什么 PHP 会这样做!?
欢迎任何解决方法...
最佳答案
如果您不传递 $initial
值,PHP 会假定它是 NULL
并将传递 NULL
给您的函数。因此,一种可能的解决方法是检查代码中的 NULL
:
function wrapper($a, $b) {
if ($a === null) {
$a = "One";
}
return str_reduc($a, $b);
}
$arr = array('Two', 'Three', 'Four');
echo array_reduce($arr, 'wrapper');
关于php - PHP 的 array_reduce 整数第三个参数的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1571997/