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

前端 未结 11 2111
[愿得一人]
[愿得一人] 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:43

    Here's what I came up with:

    $arr = array(
                'H' => 'G',
                'F' => 'G',
                'G' => 'D',
                'E' => 'D',
                'A' => 'E',
                'B' => 'C',
                'C' => 'E',
                'D' => null );
    
        $nested = parentChild($arr);
        print_r($nested);
    
        function parentChild(&$arr, $parent = false) {
          if( !$parent) { //initial call
             $rootKey = array_search( null, $arr);
             return array($rootKey => parentChild($arr, $rootKey));
          }else { // recursing through
            $keys = array_keys($arr, $parent);
            $piece = array();
            if($keys) { // found children, so handle them
              if( !is_array($keys) ) { // only one child
                $piece = parentChild($arr, $keys);
               }else{ // multiple children
                 foreach( $keys as $key ){
                   $piece[$key] = parentChild($arr, $key);
                 }
               }
            }else {
               return $parent; //return the main tag (no kids)
            }
            return $piece; // return the array built via recursion
          }
        }
    

    outputs:

    Array
    (
        [D] => Array
            (
                [G] => Array
                    (
                        [H] => H
                        [F] => F
                    )
    
                [E] => Array
                    (
                        [A] => A
                        [C] => Array
                            (
                                [B] => B
                            )    
                    )    
            )    
    )
    

提交回复
热议问题