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

PHP中如何为深度关联的数据结构查找父节点?能否移除前置元素?

如何移除parentItems函数中的previous_item变量

问题背景

我们有一个数据结构,其中每个元素除其他信息外,还会存储自身的深度值。其对应的父节点是之前出现的深度值更小的最近元素,示例如下:

A:depth 0
B:depth 1
C:depth 1
D:depth 2
E:depth 1
F:depth 2
G:depth 0
H:depth 1
I:depth 1

对应的父节点关系为:

  • A: root
  • B: A
  • C: A
  • D: C
  • E: A
  • F: E
  • G: root
  • H: G
  • I: G

当前实现代码

我编写的PHP代码如下:

<?php
  function parentItems(\ArrayAccess|\Traversable $items, object $root_object): \SplObjectStorage {
    $parent_stack =  new \SplStack();
    $parent_items = new \SplObjectStorage();
    // The tree starts with the root.
    $previous_item = $root_object;
    // Top level items have a depth of 0 and the root needs to be even less
    // deep.
    $previous_depth = -1;
    foreach ($items as $item) {
      $depth = (int) $item->getDepth();
      // if the current depth is higher than the previous one then the
      // previous item is the current parent.
      if ($depth > $previous_depth) {
        $parent_stack->push($previous_item);
      }
      // On the other hand, if the current element is less deep than the
      // previous one, then the previous parents are no longer needed.
      elseif ($depth < $previous_depth) {
        for ($i = 0; $i < $previous_depth - $depth; $i++) {
          $parent_stack->pop();
        }
      }
      // At this point, the stack top contains the current parent.
      $parent_items[$item] = $parent_stack->top();
      $previous_depth = $depth;
      $previous_item = $item;
    }
    return $parent_items;
  }
// Example dataset
$depths = [0,1,2,1,2,2,3,1,1,1,0,1,2,0,0,0,1,2,1,1,0,1,0,1,1,0,1,2,2,1,0,1,1,0,1,1,0,1,1,1,0,1,2,3,3,0,0,0,];
$a = new ArrayObject();
foreach ($depths as $depth) {
  $a[] = new class($depth) {
    protected $depth;
    function __construct($depth) { $this->depth = $depth; }
    function getDepth() { return $this->depth; }
  };
}
parentItems($a);
?>

疑问

该代码逻辑相对清晰且可正常运行,但保留previous_item的设计让我感觉不妥,虽不确定原因,但总觉得不合理。能否移除该元素?尽管数组拥有prev()方法,但据我所知迭代器并无类似方法。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:06:32