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

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

    Yet Another Function To Make A Tree (no recursion involved, uses references instead):

    $array = array('H' => 'G', 'F' => 'G', ..., 'D' => null);
    
    function to_tree($array)
    {
        $flat = array();
        $tree = array();
    
        foreach ($array as $child => $parent) {
            if (!isset($flat[$child])) {
                $flat[$child] = array();
            }
            if (!empty($parent)) {
                $flat[$parent][$child] =& $flat[$child];
            } else {
                $tree[$child] =& $flat[$child];
            }
        }
    
        return $tree;
    }
    

    Returns an hierarchical array like this one:

    Array(
        [D] => Array(
            [G] => Array(
                [H] => Array()
                [F] => Array()
            )
            ...
        )
    )
    

    Which can easily be printed as a HTML list using recursive function.

提交回复
热议问题