Table

enter image description here

How to pull out the entire chain in a loop, for example, behind a record where id is found in parent_fid

Here is an example of my code.

$array_folderid = array(); $startfor = 0; $folderdel_id = "155"; for($i=0;$i<=$startfor;$i++) { $sql_selectfolders = "SELECT * FROM user_folders WHERE parent_fid='$folderdel_id' "; $query_selectfolders = mysqli_query($db,$sql_selectfolders) or die("Ошибка: " . mysqli_error($db)); if (mysqli_num_rows($query_selectfolders) > 0) { while ($fid = mysqli_fetch_array($query_selectfolders)) { array_push($array_folderid, $fid["id"]); } } } 

In this way I get this array.

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

But now how to repeat the cycle with this data, that is, now I need to pull out all id by the fact that it is in the array. And the depth can be unpredictable.

I myself could not solve this problem, please help.

  • И глубина может бить не предсказуема in this case need recursion. If only as part of the test task - it will do. But in the working application it will slow down. - Goncharov Alexander
  • @GoncharovAleksandr, I get stuck on LAN :) - Tokwiro
  • Then look for "recursive sampling of SQL PHP tree". Because your task is to simply build a tree from a "flat" table - in general, this is a frequent task. What has the option with recursion on the SQL itself. I will not answer - since there are a lot of solutions you can google. - Goncharov Alexander
  • one
    Make only one query to the table, and then build a tree from the resulting array. - Visman
  • reference (eng) . As it is written in the answer, in mysql (and you never wrote which database you are using) there are no built-in tools for performing recursive queries. Such functionality is in postgre, for example (and some more). But in general, it is generally not recommended to store such structures in the database (as comrade writes below). In 99% of cases, you can do without it, you just need to think how. - Alexander Belinsky

0