如果同一个孩子有多个父母,如何从多维数组中列出父子关系


How to list parent child relationship from multidimentional array if the same child has multiple parents

我有一个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的子级,但它们只列出一次。在这种情况下,如果同一个孩子有多个父母,我如何列出亲子关系?非常感谢。

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

如果更改数组结构以防止覆盖键,则应该会看到子项同时列在父项下。