我想使用 RecursiveIterator 接口遍历嵌套对象。HeadHunterEntity 对象可以有许多 CandidateEntities。我想在主循环中迭代所有 CandidateEntities,但是出了点问题。
我有这样的主循环:
$iterator = new RecursiveIteratorIterator(new RecursiveHunterCandidatesIterator(new RecursiveArrayIterator($this->getHeadHunters())));
foreach ($iterator as $object) {
echo('<br>MAIN LOOP: ' . (is_object($object) ? get_class($object) : $object));
}
RecursiveHunterCandidatesIterator
class RecursiveHunterCandidatesIterator extends RecursiveFilterIterator {
public function accept() {
echo "<br>RecursiveHunterCandidatesIterator (accept) hasChildren: " . $this->hasChildren();
return $this->hasChildren();
}
public function hasChildren() {
$current = $this->current();
echo "<br>RecursiveHunterCandidatesIterator (hasChildren) current Class: " . get_class($current);
return is_object($this->current()) ? (boolean)count($this->current()->getHuntedCandidates()) : FALSE;
}
public function getChildren() {
echo "<br>RecursiveHunterCandidatesIterator (getChildren) count: " . count($this->current()->getHuntedCandidates());
$childIterator = new RecursiveArrayIterator($this->current()->getHuntedCandidates());
$childIterator2 = new RecursiveArrayIterator(array(1,2,3));
return $childIterator;
}
}
结果出乎意料,我在主循环中什么都没有:(
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
RecursiveHunterCandidatesIterator (accept) hasChildren: 1
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
RecursiveHunterCandidatesIterator (getChildren) count: 2
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
RecursiveHunterCandidatesIterator (accept) hasChildren:
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
RecursiveHunterCandidatesIterator (accept) hasChildren:
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
但是,如果我返回 $childIterator2 ,则主循环中会出现预期的结果:
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
RecursiveHunterCandidatesIterator (accept) hasChildren: 1
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
RecursiveHunterCandidatesIterator (getChildren) count: 2
MAIN LOOP: 1
MAIN LOOP: 2
MAIN LOOP: 3
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
RecursiveHunterCandidatesIterator (accept) hasChildren:
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
RecursiveHunterCandidatesIterator (accept) hasChildren:
RecursiveHunterCandidatesIterator (hasChildren) current Class: HeadHunterEntity
$this->current()->getHuntedCandidates() 返回数组,所以它应该在主循环中,就像 $childIterator2 中的 fake 1,2,3 aray ...
我做错了什么?