fork download
  1. <?php
  2.  
  3. $list = array(
  4. array("id" => 1, "parentId" => null, "text" => "Первая строка"),
  5. array("id" => 2, "parentId" => 3, "text" => "Вторая строка"),
  6. array("id" => 3, "parentId" => 1, "text" => "Третья строка"),
  7. array("id" => 4, "parentId" => 1, "text" => "Четвертая строка"),
  8. array("id" => 5, "parentId" => null, "text" => "Пятая строка"),
  9. array("id" => 6, "parentId" => 5, "text" => "Шестая строка"),
  10. ["id" => 7, "parentId" => 6, "text" => "Седьмая строка"],
  11. ["id" => 8, "parentId" => 5, "text" => "Восьмая строка"],
  12. );
  13.  
  14. /*
  15.  * 1 -> 3 -> 2
  16.  * \
  17.  * -> 4
  18.  *
  19.  * 5 -> 6 -> 7
  20.  * \
  21.  * -> 8
  22.  */
  23.  
  24. $roots = array_filter($list, function ($node) {
  25. return $node['parentId'] === null;
  26. });
  27.  
  28. $stack = array_map(function ($root) {
  29. return [0, $root];
  30. }, $roots);
  31.  
  32. function visit($depth, $node) {
  33. echo str_repeat('-', $depth) . $node['id'] . "\n";
  34. }
  35.  
  36. while (count($stack)) {
  37. list($depth, $current) = array_shift($stack);
  38.  
  39. visit($depth, $current);
  40.  
  41. $currentChildren = array_filter($list, function ($node) use ($current) {
  42. return $node['parentId'] === $current['id'];
  43. });
  44. $depthChildMap = array_map(function ($child) use ($depth) {
  45. return [$depth + 1, $child];
  46. }, $currentChildren);
  47.  
  48. $stack = array_merge($depthChildMap, $stack);
  49. }
  50.  
Success #stdin #stdout 0s 82880KB
stdin
Standard input is empty
stdout
1
-3
--2
-4
5
-6
--7
-8