Convert a series of parent-child relationships into a hierarchical tree?

前端 未结 11 2053
[愿得一人]
[愿得一人] 2020-11-22 07:04

I have a bunch of name-parentname pairs, that I\'d like to turn into as few heirarchical tree structures as possible. So for example, these could be the pairings:

         


        
11条回答
  •  误落风尘
    2020-11-22 07:49

    Well, to parse into ULs and LIs, it would be something like:

    $array = array (
        'H' => 'G'
        'F' => 'G'
        'G' => 'D'
        'E' => 'D'
        'A' => 'E'
        'B' => 'C'
        'C' => 'E'
        'D' => 'NULL'
    );
    
    
    recurse_uls ($array, 'NULL');
    
    function recurse_uls ($array, $parent)
    {
        echo '
      '; foreach ($array as $c => $p) { if ($p != $parent) continue; echo '
    • '.$c.'
    • '; recurse_uls ($array, $c); } echo '
    '; }

    But I'd love to see a solution that doesn't require you to iterate through the array so often...

提交回复
热议问题