The easiest way to build a tree from the list of ancestors

In my heart, I feel that there must be a super-simple recursive solution for this, but I cannot immediately see it.

I have a tree stored in SQL as a closure table. The tree looks like this: (1 (2 (3), 4)), and the languages ​​are MySQL SQL and PHP 5.3.

The closing table is as follows:

+----------+------------+
| ancestor | descendant |
+----------+------------+
|        1 |          1 | 
|        2 |          2 | 
|        3 |          3 | 
|        4 |          4 | 
|        1 |          2 | 
|        1 |          3 | 
|        1 |          4 | 
|        2 |          3 | 
+----------+------------+

I can query ancestors quite easily with:

 SELECT descendant AS id, GROUP_CONCAT(ancestor) as ancestors FROM
 closure GROUP BY (descendant);

 +----+-----------+
 | id | ancestors |
 +----+-----------+
 |  1 | 1         | 
 |  2 | 2,1       | 
 |  3 | 3,1,2     | 
 |  4 | 4,1       | 
 +----+-----------+

How can I easily build a tree in PHP with this data? Can I use a more intelligent query to pull more data from MySQL?

+5
source share
2 answers

- SQL . PHP, .

, .

Array
(
    [1] => Array
        (
            [0] => 1
        )

    [4] => Array
        (
            [0] => 4
            [1] => 1
        )

    [2] => Array
        (
            [0] => 2
            [1] => 1
        )

    [3] => Array
        (
            [0] => 3
            [1] => 1
            [2] => 2
        )

)

, . .

  function add_node($ancestors, &$tree) {
    if (count($ancestors) == 1) {
      $tree[array_pop($ancestors)] = array();
      return;
    }   
    $next_node = array_intersect($ancestors, array_keys($tree));
    $this->add_node(
        array_diff($ancestors, $next_node) , 
        $tree[array_pop($next_node)]
        );  
  }
+4

( ... , / , - ), "" , () ( ..).

, , , .

:

PHP, , , SELECT GROUP_CONCAT - , ?

, ( ).

, , , , .

+2

All Articles