PHP COUNT_RECURSIVE 和 SplFixedArray

标签 php spl

当与 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 不允许参数,因此您不能递归计数。 The argument is ignored.您可以从 SplFixedArray::count 的方法签名中看到这一点和 Countable::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

关于PHP COUNT_RECURSIVE 和 SplFixedArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12284818/

相关文章:

php - 低于 1 秒 mysql.connect_timeout - 可能吗?愿意编辑php源码

php - 服务器根目录总是显示欢迎使用 Nginx

php - 如何使用 RegexIterator::REPLACE 模式?

用于 SimpleXML 对象的 PHP array_walk_recursive()?

php - 如何对 SplFixedArray 进行排序?

php - 为什么我必须倒回 IteratorIterator

php - 从magento安装中的php文件运行自定义sql

php - cakephp 3.2 中同一张表上的模型关联(用于菜单和子菜单概念)

php - Objective-C 默认参数值

PHP 在子文件夹中使用 spl_autoload_register 自动加载