【发布时间】:2011-07-04 12:16:00
【问题描述】:
我正在尝试为 cmets 列表创建一个类似 this one 的迭代器:
// 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): ?>
<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; ?>
所以一切正常,除了一件事:我不知道如何处理嵌套的 cmets :(
$comments 数组返回一个平面的 cmets 列表,例如:
[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'
)
...
我需要能够以某种方式检查子 cmets(在多个级别上)并将它们插入到其父 cmets 的 </li> 之前...
有什么想法吗?
【问题讨论】:
标签: php oop class iterator nested-loops