我从表格
的adLDAP获得了结果集OU=LEAF1,OU=PARENT1,OU=ROOT,DC=datacenter,DC=local
OU=PARENT1,OU=ROOT,DC=datacenter,DC=local
OU=ROOT,DC=datacenter,DC=local
OU=LEAF2,OU=CHILD,OU=PARENT2,OU=ROOT,DC=datacenter,DC=local
OU=CHILD,OU=PARENT2,OU=ROOT,DC=datacenter,DC=local
OU=PARENT2,OU=ROOT,DC=datacenter,DC=local
其中每一行都是数组中的字符串元素。 它代表的树结构是:
Root
|--Parent1
|--Leaf1
|--Parent2
|--Child
|--Leaf2
我想生成这个
<ul>
<li>root
<ul>
<li>Parent1
<ul>
<li>leaf1</li>
</ul>
</li>
<li>Parent2
<ul>
<li>Child
<ul>
<li>Leaf2</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>
</ul>
我知道我需要向后处理字符串,而且我知道解决方案是递归的,但是周五下午,我已经做了很长时间而且我的大脑卡住了。
答案 0 :(得分:2)
这是我的尝试:
<?php
$lines = array(
'OU=LEAF1,OU=PARENT1,OU=ROOT,DC=datacenter,DC=local',
'OU=PARENT1,OU=ROOT,DC=datacenter,DC=local',
'OU=ROOT,DC=datacenter,DC=local',
'OU=LEAF2,OU=CHILD,OU=PARENT2,OU=ROOT,DC=datacenter,DC=local',
'OU=CHILD,OU=PARENT2,OU=ROOT,DC=datacenter,DC=local',
'OU=PARENT2,OU=ROOT,DC=datacenter,DC=local',
);
//build tree structure
$tree = array();
foreach ($lines as $line) {
$ancestry = getLineAncestry($line);
$node = & $tree;
foreach ($ancestry as $nodeName) {
if (! isset($node[$nodeName])) {
$node[$nodeName] = array();
}
$node = & $node[$nodeName];
}
}
print makeUl($tree);
//recurse through tree to build unordered-list
function makeUl($array) {
$result = '<ul>';
foreach ($array as $nodeName => $children) {
$result .= '<li>' . ucfirst($nodeName);
if (count($children)) {
$result .= makeUl($children);
}
$result .= '</li>';
}
$result .= '</ul>';
return $result;
}
function getLineAncestry($line) {
$result = array();
$params = explode(',', $line);
foreach ($params as $param) {
$tmp = explode('=', $param);
if ($tmp[0] == 'OU') {
$result[] = $tmp[1];
}
}
$result = array_reverse($result);
return $result;
}