我正致力于解决 HackerRank 上的“一个非常大的数字”。目标是在不使用 array_sum 的情况下生成数组中所有元素的总和。为清楚起见,我此处的示例代码与此处的代码略有不同。
这个有效:
$arr = array(
1000000001,
1000000002,
1000000003,
1000000004,
1000000005
);
$total = 0;
array_walk($arr, 'totalize');
echo '*' . $total;
function totalize( $arr_item ) {
global $total;
$total += $arr_item;
}
我想避免使用全局变量,这样我可以在将来使用回调函数时正确地做事。但是,这不起作用。我将在代码后显示输出:
$arr = array(
1000000001,
1000000002,
1000000003,
1000000004,
1000000005
);
$total = 0;
array_walk($arr, 'totalize', $total);
echo '*' . $total;
function totalize( $arr_item, $key, &$total ) {
$total += $arr_item;
echo $arr_item . '.' . $key . '.' . $total . '<br />';
}
它给出了这个作为输出:
1000000001.0.1000000001
1000000002.1.2000000003
1000000003.2.3000000006
1000000004.3.4000000010
1000000005.4.5000000015
*0
为什么 $total 加起来正确但后来被放弃了?
最佳答案
array_walk()
传递给回调的第三个参数不是通过引用传递的,无论您在回调的签名中放入什么。对于这种特殊情况,您可以使用 anonymous function与 the use
keyword通过引用将 $total
导入函数的作用域。
$arr = [
1000000001, 1000000002, 1000000003, 1000000004, 1000000005
];
$total = 0;
array_walk($arr, function ($arr_item) use (&$total) {
echo ($total += $arr_item) . "\n";
});
echo '*' . $total;
关于PHP 回调函数和变量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37011395/