在使用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对象而导致的正常行为?
发布于 2012-09-05 23:30:44
SplFixedArray实现了Countable,但Countable不允许参数,因此不能计算递归。从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
https://stackoverflow.com/questions/12284818
复制相似问题