2009-09-18 4 views
0

J'ai un jeu de résultats adLDAP de la formePhp: Générer arbre ul-li à partir du répertoire actif résulte

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 

où chaque ligne est un élément de chaîne dans un tableau. La structure de l'arbre qu'il représente est:

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

et je veux générer ce

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

Je sais que je dois traiter les chaînes en arrière, et je sais que la solution est récursive, mais il est vendredi après-midi , il y a longtemps que je l'ai fait et mon cerveau est bloqué.

Répondre

2

Voici ma tentative:

<?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; 
} 
+0

semble être juste l'affaire. Beaucoup, merci beaucoup Tom. –

Questions connexes