简体   繁体   中英

PHP COUNT_RECURSIVE and SplFixedArray

I'm seeing some odd behavior with count( $arr, COUNT_RECURSIVE ) when used with SplFixedArray . 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?

SplFixedArray implements Countable , but Countable does not allow for a arguments, hence you cannot count recursive. The argument is ignored. You can see this from the method signature of SplFixedArray::count and Countable::count .

There is a Feature Request open for this at 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. 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;
    }
}

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM