因此,我编写了一些相当复杂的“功能性”PHP 代码来对数组执行折叠。别担心,我不会在任何地方使用它。问题是,PHP 的“每个”函数似乎只到达数组的末尾,因为它是静态声明的(实际上,见底部)。
// declare some arrays to fold with
$six = array("_1_","_2_","_3_","_4_","_5_","_6_");
// note: $ns = range(0,100) won't work at all--lazy evaluation?
$ns = array(1,2,3,4,5,6,7,8);
$ns[8] = 9; // this item is included
// add ten more elements to $ns. each can't find these
for($i=0; $i<10; ++$i)
$ns[] = $i;
// create a copy to see if it fixes 'each' problem
$ms = $ns;
$ms[0] = 3; // Just making sure it's actually a copy
$f = function( $a, $b ) { return $a . $b; };
$pls = function( $a, $b ) { return $a + $b; };
function fold_tr( &$a, $f )
{
$g = function ( $accum, &$a, $f ) use (&$g)
{
list($dummy,$n) = each($a);
if($n)
{
return $g($f($accum,$n),$a,$f);
}
else
{
return $accum;
}
};
reset($a);
return $g( NULL, $a, $f );
}
echo "<p>".fold_tr( $six, $f )."</p>"; // as expected: _1__2__3__4__5__6_
echo "<p>".fold_tr( $ns, $pls )."</p>"; // 45 = sum(1..9)
echo "<p>".fold_tr( $ms, $pls )."</p>"; // 47 = 3 + sum(2..9)
老实说,我不知道每个人如何保持自己的状态。充其量似乎是退化的,因为语言中有更好的(非魔法)机制来遍历列表,但是有谁知道为什么它会使用$a[$index] = value
而不是'$a [] = value'来注册添加到数组中的项目?在此先感谢您对此行为的任何见解。