【发布时间】:2013-08-27 07:32:32
【问题描述】:
属性parent 返回当前项的父项(或null)。我需要避免对其自身的父项进行无限递归。
// An item is considered without parent if parent is null or itself
$item1 = new Item();
$item1->setParent($item1);
$item2 = new Item();
$item2->setParent($item1);
$item3 = new Item();
$item3->setParent($item2);
$item1->getAncestors(); // Empty
$item2->getAncestors(); // Item 1
$item2->getAncestors(); // Item 1, Item 2
以下将不起作用,因为第一个条件是 true 表示“有问题”$item(因此不评估第二个条件):
/**
* Gets all ancestors of this item, sorted in a way that the farthest ancestor
* comes first.
*
* @return \Doctrine\Common\Collections\ArrayCollection
*/
public function getAncestors()
{
$parent = $this;
$ancestors = array();
while ($parent = $parent->parent && $this !== $parent) {
$ancestors[] = $parent;
}
return new ArrayCollection(array_reverse($ancestors));
}
这也行不通,因为在循环 1 上 $this 是 $parent:
while ($this !== $parent && $parent = $parent->parent) {
$ancestors[] = $parent;
}
我确定这是一个常见问题,但我自己找不到解决方案。
【问题讨论】:
标签: php recursion hierarchy php-5.3 hierarchical