2012-09-05 11 views
4

使用SplFixedArray時,我看到count($ arr,COUNT_RECURSIVE)有一些奇怪的行爲。就拿這個代碼塊,比如...PHP COUNT_RECURSIVE和SplFixedArray

$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對象?

回答

6

SplFixedArray implements Countable,但Countable不允許參數,因此您不能計數遞歸。 The argument is ignored.您可以從方法簽名SplFixedArray::countCountable::count中看到。

還有一個特點,要求開放此在https://bugs.php.net/bug.php?id=58102


可以sublass 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

+1

正是我一直在尋找。今天早上我檢查了一下,但沒有找到任何東西。我知道我忽略了一些東西。謝謝! – wlvrn