adam copeland
adam copeland

Reputation: 31

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

I have mysql query which will return data from tbl_posts as an array. The array shows the parent child relationship between them as follows

$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
    );

Here P1, P2, P3 are parent posts and C1, C2, C3.. are child posts and GC1, GC2, GC3...are grand child according to the array which was returned by the query. I want to list these data according to the parent child relationship as below

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

  -- C2
    --- GC1
    --- GC2 

- P2
  -- C3

-P3
  -- C4
    --- GC2

I have tried this code as below

   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);

And i got the result as below

P1
    C1
    C2
      GC1

P2
    C3

P3
    C4
      GC2

The grand child are are listed only once. GC1, GC2, and GC3 are child of C1, C2 and C3 but they are listed only once. How can i list the parent child relationship if the same child has multiple parents in such case? Thank you.

Upvotes: 1

Views: 53

Answers (1)

solocommand
solocommand

Reputation: 327

In your example you are defining duplicate keys in your array GC1 belongs to a single parent (C2) because GC1 => C2 overwrote the previous entry.

If you change your array structure around to prevent overwriting keys, you should see the child then listed under both parents.

Upvotes: 1

Related Questions