繁体   English   中英

PHP COUNT_RECURSIVE和SplFixedArray

[英]PHP COUNT_RECURSIVE and SplFixedArray

SplFixedArray一起使用时,我看到count($ arr,COUNT_RECURSIVE)出现一些奇怪的行为。 以这段代码为例...

$structure = new SplFixedArray( 10 );

for( $r = 0; $r < 10; $r++ )
{
    $structure[ $r ] = new SplFixedArray( 10 );
    for( $c = 0; $c < 10; $c++ )
    {
        $structure[ $r ][ $c ] = true;
    }
}

echo count( $structure, COUNT_RECURSIVE );

结果...

> 10

您期望得到的结果是110。这是否是由于我嵌套了SplFixedArray对象而导致的正常行为?

SplFixedArray实现Countable ,但是Countable不允许使用参数,因此您不能计算递归。 该参数被忽略。 您可以从SplFixedArray::countCountable::count的方法签名中看到这一点。

https://bugs.php.net/bug.php?id=58102上为此打开了功能请求


您可以对SplFixedArray进行SplFixedArray并使其实现RecursiveIterator ,然后重载count方法以使用iterate_count但是它将始终对所有元素进行计数,例如,则始终为COUNT_RECURSIVE 虽然也可以添加专用方法。

class MySplFixedArray extends SplFixedArray implements RecursiveIterator
{
    public function count()
    {
        return iterator_count(
            new RecursiveIteratorIterator(
                $this,
                RecursiveIteratorIterator::SELF_FIRST
            )
        );
    }

    public function getChildren()
    {
        return $this->current();
    }

    public function hasChildren()
    {
        return $this->current() instanceof MySplFixedArray;
    }
}

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM