【问题标题】:Simple recursive object hierarchy in PHP, how to get ancestors avoiding infinite loop?PHP中的简单递归对象层次结构,如何让祖先避免无限循环?
【发布时间】: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


    【解决方案1】:

    正如您所说,您正在遍历的结构不是一棵树。这是一个带循环的有向图。避免无限循环的一种方法是通过传递包含所有已访问顶点的数组列表来跟踪已访问顶点。当您访问每个顶点时,您首先检查它是否在列表中,如果为真则返回,否则将其添加到列表中并继续。您不需要递归。一个while循环就可以了。

    【讨论】:

    • 一个孩子不能有多个父母,所以不是一棵树吗?
    • 不,这不是充分条件。你不应该有任何循环。有关树的正式定义,请参阅 en.m.wikipedia.org/wiki/Ordered_tree 和相关链接。
    • "树数据结构可以递归地(本地)定义为节点的集合(从根节点开始),其中每个节点是由一个值组成的数据结构,以及一个对节点(“子节点”)的引用,约束条件是没有引用重复,并且没有指向根。” (维基百科)
    • 致反对者:有礼貌地发表评论解释。
    • 我是。我投了反对票,因为即使您是正确的,这也不是代码答案。这是一个维基百科链接。
    猜你喜欢
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 2020-09-04
    • 2019-05-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多