我从包含实体及其子项的多维数组构建无序列表时遇到问题。问题是我不想使用递归,因为树可能会变得很深,递归可能会在服务器上产生不必要的负载。
这是这样一个数组的一个例子(它被简化为包含title
并且children
实体也可以是对象)。
$array = array(
array('title' => '1', 'children' => array()),
array('title' => '2', 'children' => array()),
array('title' => '3', 'children' => array()),
array('title' => '4', 'children' => array(
array('title' => '41', 'children' => array()),
array('title' => '42', 'children' => array()),
array('title' => '43', 'children' => array()),
array('title' => '44', 'children' => array(
array('title' => '441', 'children' => array()),
array('title' => '442', 'children' => array()),
array('title' => '443', 'children' => array()),
array('title' => '444', 'children' => array(
array('title' => '4441', 'children' => array()),
array('title' => '4442', 'children' => array()),
array('title' => '4443', 'children' => array())
)),
)),
array('title' => '45', 'children' => array())
)),
array('title' => '5', 'children' => array()),
array('title' => '6', 'children' => array(
array('title' => '61', 'children' => array()),
array('title' => '62', 'children' => array()),
array('title' => '63', 'children' => array())
)),
array('title' => '7', 'children' => array())
);
在这里做一些研究,所以我想出了这个非常接近我想要的解决方案:
<html>
<head></head>
<body>
<ul>
<?php
$stack = $array;
$i = 0;
$counts = array();
while(!empty($stack)) {
$node = array_shift($stack);
echo "<li>{$node['title']}";
if($node['children']) {
echo "<ul>";
$counts[] = count($node['children']);
$node['children'] = array_reverse($node['children']);
foreach($node['children'] as $ch)
array_unshift($stack, $ch);
}
if(!empty($counts)) {
end($counts);
if($counts[$key] == 0) {
echo "</ul>";
array_pop($counts);
} else {
$counts[$key]--;
}
}
if(!$node['children']) {
echo "</li>";
}
// just to make sure we won't end in infinite loop
$i++;
if($i == 50) break;
}
?>
</ul>
</body>
</html>
输出如下 - 如您所见,我遇到的问题只是</ul>
子树的关闭。我的问题:我是不是想多了,还是我瞎了眼,没有看到明显的错误?您能否将我推向有限的解决方案或给我您自己的解决方案?
输出:
- 1
- 2
- 3
- 4
- 41
- 42
- 43
- 44
- 441
- 442
- 443
- 444
- 4441
- 4442
- 4443
- 45
- 5
- 6
- 61
- 62
- 63
- 7