当与SplFixedArray一起使用时,我看到了一些奇怪的行为($ 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 );
Run Code Online (Sandbox Code Playgroud)
结果...
> 10
Run Code Online (Sandbox Code Playgroud)
你会期望110的结果.这是正常的行为,因为我正在嵌套SplFixedArray对象吗?
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;
}
}
Run Code Online (Sandbox Code Playgroud)