【问题标题】:PHP COUNT_RECURSIVE and SplFixedArrayPHP COUNT_RECURSIVE 和 SplFixedArray
【发布时间】:2012-09-05 15:25:30
【问题描述】:

当与 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 对象而导致的正常行为吗?

【问题讨论】:

    标签: php spl


    【解决方案1】:

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

    https://bugs.php.net/bug.php?id=58102 对此有一个功能请求。


    您可以将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;
        }
    }
    

    demo

    【讨论】:

    • 正是我想要的。我今天早上检查过,但找不到任何东西。我知道我忽略了一些东西。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-06-18
    • 2014-03-24
    • 2014-05-21
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 2012-08-03
    • 2013-08-09
    相关资源
    最近更新 更多