PHP每个和静态数组声明

时间:2012-10-17 23:03:41

标签: php

所以,我写了一些相当复杂的'功能'PHP代码来执行数组上的折叠。别担心,我不会在任何地方使用它。问题是,PHP的'each'函数似乎只能到数组的末尾,因为它是静态的(实际上,见底部)声明。

// 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 [ ] =值`?提前感谢对此行为的任何见解。

1 个答案:

答案 0 :(得分:2)

由于PHP的弱输入,你的循环正在退出:

if($n)
{
    return $g($f($accum,$n),$a,$f);
}
else
{
    return $accum;
}

$n0时(例如$ns[9]),条件将失败,您的循环将终止。修复以下内容:

if($n !== null)
相关问题