[英]PHP COUNT_RECURSIVE and SplFixedArray
I'm seeing some odd behavior with count( $arr, COUNT_RECURSIVE ) when used with SplFixedArray . 与SplFixedArray一起使用时,我看到count($ arr,COUNT_RECURSIVE)出现一些奇怪的行为。 Take this block of code, for instance...
以这段代码为例...
$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 );
Result... 结果...
> 10
You would expect a result of 110. Is this normal behavior due to the fact that I'm nesting SplFixedArray objects? 您期望得到的结果是110。这是否是由于我嵌套了SplFixedArray对象而导致的正常行为?
SplFixedArray
implements Countable
, but Countable
does not allow for a arguments, hence you cannot count recursive. SplFixedArray
实现Countable
,但是Countable
不允许使用参数,因此您不能计算递归。 The argument is ignored. 该参数被忽略。 You can see this from the method signature of
SplFixedArray::count
and Countable::count
. 您可以从
SplFixedArray::count
和Countable::count
的方法签名中看到这一点。
There is a Feature Request open for this at https://bugs.php.net/bug.php?id=58102 在https://bugs.php.net/bug.php?id=58102上为此打开了功能请求
You can sublass SplFixedArray
and make it implement RecursiveIterator
and then overload the count
method to use iterate_count
but then it will always count all the elements, eg it's always COUNT_RECURSIVE
then. 您可以对SplFixedArray进行
SplFixedArray
并使其实现RecursiveIterator
,然后重载count
方法以使用iterate_count
但是它将始终对所有元素进行计数,例如,则始终为COUNT_RECURSIVE
。 Can also add a dedicated method though. 虽然也可以添加专用方法。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.