views:

429

answers:

1

I've got a result set from adLDAP of the form

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

Where each line is a string element in an array. The tree structure it represents is :

Root
  |--Parent1
       |--Leaf1
  |--Parent2
       |--Child
            |--Leaf2

and I want to generate this

<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>

I know I need to process the strings backwards, and I know the solution is recursive, but it's friday afternoon, it's a long time since I've done it and my brain is stuck.

+1  A: 

Here is my attempt:

<?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;
}
Tom Haigh
Looks to be just the trick. Many, many thanks Tom.
WaveyDavey