我尝试在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());
如果没有递归,我想实现的目标是什么?不幸的是,我的代码将所有内容添加为父...
谢谢!
答案 0 :(得分:2)
不是真的,你需要递归。无论如何递归都不是问题,但你会经常迭代这些项目。因此,为了避免这种情况,您需要以可以通过id访问它的方式存储数据:
$items = [];
$index = [];
foreach ($data as $item) {
$items[$item['product_id']] = $item;
$index[$item['parent']][] = $item['product_id'];
}
$items
按product_id
提供商品。 $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>