Sto cercando di creare un iteratore come this one, per un elenco di commenti:implementazione multi-livello "iteratore" in 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]);
}
}
Il commento iteratore:
class MyCommentIterator extends MyIterator{
public function current(){
return new Comment($this->list[$this->position]);
}
}
E questo è come lo uso:
$comments = GetComments(); // gets the comments from the db
if($comments): ?>
<ol>
<?php foreach(new MyCommentIterator($comments) as $comment): ?>
<li>
<p class="author"><?php echo $comment->author(); ?></p>
<div class="content">
<?php echo $comment->content(); ?>
</div>
<!-- check for child comments and display them -->
</li>
<?php endforeach; ?>
</ol>
<?php endif; ?>
Quindi tutto funziona bene, oltre a una cosa: non riesco a capire come elaborare n commenti INTERESSATE :(
L'array $comments
restituisce una semplice lista di commenti, come:
[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'
)
...
ho bisogno di essere in qualche modo in grado di verificare la presenza di commenti bambino (su più livelli) e inserirli prima della </li>
' s dei loro commenti principali ...
Qualche idea?