2016-01-10 103 views
1

我有mysql查询,它将以tbl_posts的形式返回数据作为数组。该阵列显示如下如何从多维数组中列出父亲子女关系,如果同一孩子有多个父母

$tree = array(
     'C1' => 'P1',//C1 is the child of P1 
     'C2' => 'P1',//C2 is the child of P1 
     'C3' => 'P2',//C3 is the child of P1 
     'C4' => 'P3',//C4 is the child of P1 
     'GC1' => 'C1',//GC1 is the child of C1 
     'GC1' => 'C2',//GC1 is the child of C2 
     'GC2' => 'C1',//GC2 is the child of C1 
     'GC2' => 'C2',//GC2 is the child of C2 
     'GC2' => 'C4',//GC2 is the child of C4 

     'P1' => null,//parent post P1 
     'P2' => null,//parent post P2 
     'P3' => null,//parent post P3 
    ); 

这里P1,P2,P3是父职位,C1,C2,C3 ..是孩子的职位和GC1,GC2他们之间的父子关系,GC3 ......是盛大孩子根据查询返回的数组。 我想按照如下

- P1 
    -- C1 
    --- GC1 
    --- GC2 

    -- C2 
    --- GC1 
    --- GC2 

- P2 
    -- C3 

-P3 
    -- C4 
    --- GC2 

的父子关系列出这些数据我已经尝试了这种代码如下

function parseTree($tree, $root = null) { 
    $return = array(); 
    foreach($tree as $child => $parent) { 
     if($parent == $root) { 
      $return[] = array(
      'parent' => $child, 
      'child' => parseTree($tree, $child) 
     ); 
     } 
    } 
    return empty($return) ? null : $return;  
} 

function printTree($tree) { 
if(!is_null($tree) && count($tree) > 0) { 
    echo '<ul>'; 
    foreach($tree as $node) { 
     echo '<li>'.$node['parent']; 
     printTree($node['child']); 
     echo '</li>'; 
    } 
    echo '</ul>'; 
    } 
} 

$result = parseTree($tree); 

echo "<pre>"; 
printTree($result); 

,我得到的结果如下

P1 
    C1 
    C2 
     GC1 

P2 
    C3 

P3 
    C4 
     GC2 

大孩子只被列出一次。 GC1,GC2和GC3是C1,C2和C3的子码,但它们只列出一次。如果同一个孩子在这种情况下有多个父母,我如何列出父母亲的关系?谢谢。

回答

1

在您的示例中,您正在定义数组中的重复键GC1属于单个父(C2),因为GC1 => C2覆盖了上一个条目。

如果更改阵列结构以防止覆盖键,则应该看到父子双方都列出的子项。