PHP中HTML的实体化路径


Materialized Path to HTML in PHP

我尝试在PHP中将物化路径转换为HTML。这是我的数据结构:

Array
(
    [0] => Array
        (
            [product_id] => 7
            [name] => Parent 1
            [parent] => 
            [deep] => 
            [lineage] => 00007
        )
    [1] => Array
        (
            [product_id] => 9
            [name] => Child of Parent 1
            [parent] => 7
            [deep] => 1
            [lineage] => 00007-00009
        )
    [2] => Array
        (
            [product_id] => 12
            [name] => Child of Child 1
            [parent] => 9
            [deep] => 2
            [lineage] => 00007-00009-00012
        )
    [3] => Array
        (
            [product_id] => 10
            [name] => Parent 2
            [parent] => 
            [deep] => 
            [lineage] => 00010
        )
    [4] => Array
        (
            [product_id] => 11
            [name] => Child of Parent 2
            [parent] => 10
            [deep] => 1
            [lineage] => 00010-00011
        )
)

我想实现这样的目标:

<ul>
   <li >
     <a href="#">Parent</a>
     <ul>
        <li><a href="#">Child</a></li>
     </ul>
  </li>
</ul>

这是我的代码:

$doc = new DOMDocument();
foreach ($list as $node) {
   $element = $doc->createElement('li', $node['name_de']);
   $parent = $doc->appendChild($element);
}
echo ($doc->saveHTML());

在没有递归的情况下,我想要实现的目标是可能的吗?不幸的是,我的代码将所有内容都添加为父级。。。

谢谢!

不是真的,你需要递归。无论如何,递归不是问题所在,但您会经常迭代项。因此,为了避免这种情况,你需要以一种可以通过id:访问的方式存储数据

$items = [];
$index = [];
foreach ($data as $item) {
  $items[$item['product_id']] = $item;
  $index[$item['parent']][] = $item['product_id'];
}

CCD_ 1通过CCD_ 2提供项目。$index允许获取项目的子项。

现在,函数可以附加项,检查是否有子项,附加ul并为每个子项调用自己。

function appendItem('DOMNode $parentNode, $itemId, array $items, array $index) {
  $dom = $parentNode->ownerDocument;
  if ($item = $items[$itemId]) {
    $node = $parentNode->appendChild($dom->createElement('li'));
    $node->appendChild($dom->createTextNode($item['name']));
    if (isset($index[$itemId]) && is_array($index[$itemId])) {
      $list = $node->appendChild($dom->createElement('ul'));
      foreach ($index[$itemId] as $childItemId) {
        appendItem($list, $childItemId, $items, $index);
      }
    }
  }
}
$dom = new DOMDocument();
$parentNode = $dom->appendChild($dom->createElement('ul'));
foreach ($index[0] as $itemId) {
  appendItem($parentNode, $itemId, $items, $index);
}
$dom->formatOutput = TRUE;
echo $dom->saveXml();

输出:

<?xml version="1.0"?>
<ul>
  <li>Parent 1<ul><li>Child of Parent 1<ul><li>Child of Child 1</li></ul></li></ul></li>
  <li>Parent 2<ul><li>Child of Parent 2</li></ul></li>
</ul>