当与 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;
}
}
关于PHP COUNT_RECURSIVE 和 SplFixedArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12284818/