首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP COUNT_RECURSIVE和SplFixedArray

PHP COUNT_RECURSIVE和SplFixedArray
EN

Stack Overflow用户
提问于 2012-09-05 23:25:31
回答 1查看 396关注 0票数 4

在使用SplFixedArray时,我发现count( $arr,COUNT_RECURSIVE )有一些奇怪的行为。以这段代码为例。

代码语言:javascript
复制
$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 );

结果...

代码语言:javascript
复制
> 10

你会期望得到110的结果。这是不是因为嵌套了SplFixedArray对象而导致的正常行为?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-05 23:30:44

SplFixedArray实现了Countable,但Countable不允许参数,因此不能计算递归。从SplFixedArray::countCountable::count的方法签名中可以看出这一点。

https://bugs.php.net/bug.php?id=58102上有一个针对此功能的公开请求

您可以子类SplFixedArray并使其实现RecursiveIterator,然后重载count方法以使用iterate_count,但它将始终计算所有元素,例如,它始终为COUNT_RECURSIVE。但是也可以添加一个专用的方法。

代码语言:javascript
复制
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;
    }
}

demo

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12284818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档