, реализующий многоуровневый «итератор» в PHP

Я пытаюсь создать итератор наподобие этого , для списка комментариев:

// the iterator class, pretty much the same as the one from the php docs...
abstract class MyIterator implements Iterator{

  public $position = 0,
         $list;

  public function __construct($list) {
    $this->list = $list;
    $this->position = 0;
  }

  public function rewind() {
    $this->position = 0;
  }

  public function current() {
    return $this->list[$this->position];
  }

  public function key() {
    return $this->position;
  }

  public function next() {
    ++$this->position;
  }

  public function valid() {
    return isset($this->list[$this->position]);
  }
}

Итератор комментариев:

class MyCommentIterator extends MyIterator{

  public function current(){
    return new Comment($this->list[$this->position]);
  }    
}

И вот как Я использую его:

$comments = GetComments(); // gets the comments from the db
if($comments): ?>

  
  1. author(); ?>

    content(); ?>

Итак, все работает нормально, кроме одного: я не могу понять, как обрабатывать вложенные комментарии: (

Массив $ comments возвращает плоский список комментариев , например:

[0] => object(
    'id' => 346,
    'parent' => 0,  // top level comment
    'author' => 'John',
    'content' => 'bla bla'         
  ),

[1] => object(
    'id' => 478,
    'parent' => 346,  // child comment of the comment with id =346
    'author' => 'John',
    'content' => 'bla bla'         
  )
...

Мне нужно каким-то образом проверить наличие дочерних комментариев (на нескольких уровнях) и вставить их перед их родительских комментариев ...

Любые идеи?

5
задан Alex 4 July 2011 в 12:16
поделиться