You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在遍历树形结构的嵌套循环中使用Yield

如何在PHP中嵌套使用yield遍历树形结构?

你当前的代码只能遍历第一层节点,问题出在递归调用iterateTree时,没有把递归生成的子节点迭代器内容传递到当前迭代器中。另外还有个小问题:子节点的父节点应该是当前遍历的$child,而不是传入的$parent。

修正后的代码如下:

public function iterateTree(array $children, ?ExtendedItemCategory $parent): iterable {
    /** @var ExtendedItemCategory $child */
    foreach ($children as $child) {
        $child->setParent($parent);

        if ($child->countChildren() > 0) {
            // 使用yield from将递归迭代器的元素逐个yield出来
            yield from $this->iterateTree($child->getChildren(), $child);
        }
        yield $child;
    }
}

关键说明:

  • yield from 的作用:PHP 5.5及以上版本支持yield from语法,它可以将另一个迭代器(或可遍历对象)的所有元素逐个输出到当前生成器中,这样递归遍历子节点时,子节点的元素就能被包含到顶层的迭代器里,实现完整的树形遍历。
  • 修正父节点赋值:递归调用时,子节点的父节点应该是当前的$child,而不是原$parent,这样才能正确构建节点的父子关系。

测试代码无需修改,现在执行遍历就能输出所有层级的节点code:

$categoriesTree = ...;

$iterable = $this->iterateTree($categoriesTree, null);
foreach ($iterable as $iter)
{
    var_dump($iter->getCode());
}

内容的提问来源于stack exchange,提问作者Claudio Ferraro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 03:35:27