It is necessary to display data from the table below in a tree form. In the table, each row is a task. Each task can have basic tasks that are tied to the base using the parent_id field (it keeps the id on the base task).

id | parent_id
1 | null
2 | one
3 | 2
4 | 2
5 | four
6 | four
7 | five
8 | five

  • 3
    I have de Ms. vu. Have you already asked this question? It seems even yesterday - tutankhamun
  • What exactly is the problem? Give an example of the code in which you want to use it. - tutankhamun
  • So it is) Formulated differently. And I don’t have the code, there is a table that I get from the database, translate it into a two-dimensional array. And now you need to make an n-dimensional array. N-dimensional because the nesting level can be any. - KRasul
  • I already wrote that you have, in fact, the task of storing a tree structure. You can store an array with wild nesting, but this is not necessary here. Formulate a task for which you want to create such an array. - tutankhamun
  • 2
    @tutankhamun, some users have taken the habit of erasing their old / closed questions and asking exactly the same new ones. - Visman

1 answer 1

I am fantasizing. We take data from the database to the $temp array, for example, as in the question

 $temp = array( array('id' => 1, 'parent_id' => null), array('id' => 2, 'parent_id' => 1), array('id' => 3, 'parent_id' => 2), array('id' => 4, 'parent_id' => 2), array('id' => 5, 'parent_id' => 4), array('id' => 6, 'parent_id' => 4), array('id' => 7, 'parent_id' => 5), array('id' => 8, 'parent_id' => 5), ); 

Rearrange the array so that it is possible to access descendants by parent index:

 $tree = array(); foreach ($temp as $row) { $tree[$row['parent_id']][] = $row['id']; } 

Determine the function to draw the "twigs" from the root id

 function printBranch($tree, $rootId, $prefix) { foreach ($tree[$rootId] as $branchId) { // Рисуем "листик" (в данном случае просто его id) echo($prefix . $branchId . "\n"); if (isset($tree[$branchId])) { // Если у этого "листика" есть "ответвление", рисуем его printBranch($tree, $branchId, $prefix . '__'); } } } 

Draw the whole tree

 printBranch($tree, '', ''); 

We get:

 1 __2 ____3 ____4 ______5 ________7 ________8 ______6 [Finished in 0.3s] 
  • Here it is! Thank you so much!)) I didn’t recurse ) - KRasul
  • You can make a stack, but to fence an array of terrible nesting here is not necessary. The task is actually quite common. - tutankhamun
  • Understood, thanks again) - KRasul
  • @KRasul Just ask to reformulate the question. Now it turns out that the answer is written to another question. Your commentary formulated a more specific task. Learn to formulate :) And you will benefit and the site will do better - tutankhamun
  • @KRasul ... besides, if “it didn’t work with recursion”, they would publish the code and explain what they wanted to do and what happens. It would be clearer and more correct - tutankhamun