【问题标题】:Did O'reilly make a mistake: array_reduceO'reilly 是否犯了一个错误:array_reduce
【发布时间】:2013-01-01 08:31:51
【问题描述】:

我正在从 O'reilly 媒体书籍“PHP 编程”中学习 PHP,我偶然发现了这一点:

function add_up ($running_total, $current_value) {
    $running_total += $current_value * $current_value;
    return $running_total;
}
$numbers = array(2, 3, 5, 7);
$total = array_reduce($numbers, 'add_up');
echo $total;

array_reduce() 行进行这些函数调用:

add_up(2,3)
add_up(11,5)
add_up(36,7)
// $total is now 87

但是当我计算时我得到 85。我认为它应该这样写:

array_reduce( ) 行进行这些函数调用:

add_up (0,2);
add_up (4,3);
add_up (13,5);
add_up (38,7);

因为可选值 $initial 默认设置为NULL

mixed array_reduce ( array $input , callable $function [, mixed $initial = NULL ] )

有更多知识的人可以向我解释一下,谁错了,为什么?

【问题讨论】:

  • 查看本书的勘误页。
  • 手动计算时得到 87。编辑:viper-7.com/CG6bZe
  • 我的意思是我在使用书中的函数调用时得到 85,而按照我的方式得到 87..

标签: php array-reduce


【解决方案1】:

已在errata 中进行了报道(虽然未得到证实)。但由于您不是唯一一个注意到的人,因此您很可能是正确的。

{128}  Section "Reducing an Array";
Reducing An Array - Example of function calls created by array_reduce();

The array reduce() line makes these function calls:

add_up(2,3)
add_up(13,5)
add_up(38,7)

The correct list of calls should be:

add_up(0,2)    // This line is missing in the book
add_up(4,3)    // This line is incorrect in the book
add_up(13,5)
add_up(38,7)


[129]  first example;
the resulting calls of the second example of array_reduce() should be:
add_up(11, 2)
add_up(15, 3)
add_up(24, 5)
add_up(49, 7)

【讨论】:

  • 这不是勘误表。这是尚未确认的问题列表,尚未发送至the errata list
  • (不过,我希望这最终会出现在勘误表中,因为它看起来是正确的。只是说。)
  • 各位感谢为我澄清这一点,我检查了未经证实的勘误表并注意到与我的相同的解决方案。再次感谢您非常快速和有用的回复。
猜你喜欢
  • 2022-10-13
  • 2014-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-20
相关资源
最近更新 更多