Recursive intersection of a simple tree in PHP

I have a simple tree that takes the form below

    ROOT
     /\
    A  B
   /    \ 
  A1     B1
          \
           B11

This is stored in the CLASSES table, which is itself bound.

 ID |  CLASS_ID  | PARENT_ID
 ---------------------------
  1 |     ROOT   |  
  2 |     A      | ROOT
  3 |     A1     | A
  4 |     B      | ROOT
  5 |     B1     | B
  6 |     B11    | B1
 ---------------------------

etc., this is just an example, the class_id and parent_id columns are integers, but I just made them symbols for this example so you understand this idea.

Then I have a second CHILDREN table, which I want to see at the end,

 ID | CLASS_ID   | CHILD_CLASS_ID
 --------------------------------
  1 |     ROOT   |  A
  2 |     ROOT   |  A1
  3 |     ROOT   |  B
  4 |     ROOT   |  B1
  5 |     ROOT   |  B11
  6 |     A      |  A1
  7 |     B      |  B1
  8 |     B      |  B11
  9 |     B1     |  B11
 ---------------------------

, , . , , PHP. mysql. , . . - A11, , A11.

+3
2

, , . , ?

, ID , MySQL GROUP_CONCAT()

SELECT PARENT_ID, GROUP_CONCAT(CLASS_ID) AS CHILDREN
FROM CLASSES
GROUP BY PARENT_ID

- :

| PARENT_ID | CHILDREN      |
-----------------------------
| ROOT      | A,A1,B,B1,B11 |
| A         | A1            |
| B         | B1,B11        |
| A1        |               |
| B1        | B11           |
| B11       |               |
-----------------------------

CHILDREN?

+2

Source: https://habr.com/ru/post/1734064/


All Articles