fork download
  1. <?php
  2.  
  3. $adjacencyList = 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. array("id" => 7, "parentId" => 6, "text" => "Седьмая строка"),
  11. array("id" => 8, "parentId" => 7, "text" => "Восьмая строка"),
  12. );
  13.  
  14. function fillWithChildren(array $adjacencyList) {
  15. $nodesWithChildren = [];
  16. foreach ($adjacencyList as $node) {
  17. if (!array_key_exists($node['parentId'], $nodesWithChildren)) {
  18. $nodesWithChildren[$node['parentId']] = [];
  19. }
  20. $nodesWithChildren[$node['parentId']][] = $node;
  21. }
  22. return $nodesWithChildren;
  23. }
  24.  
  25. function printList(array $nodes, $parentId = null, $depth = 0) {
  26. foreach ($nodes[$parentId] as $node) {
  27. visitNode($node, $depth);
  28. if (!empty($nodes[$node['id']])) {
  29. printList($nodes, $node['id'], $depth + 1);
  30. }
  31. }
  32. }
  33.  
  34. function visitNode(array $node, $depth) {
  35. echo str_repeat('-', $depth) . $node['text'] . PHP_EOL;
  36. }
  37.  
  38. printList(fillWithChildren($adjacencyList));
  39.  
Success #stdin #stdout 0.01s 52488KB
stdin
Standard input is empty
stdout
Первая строка
-Третья строка
--Вторая строка
-Четвертая строка
Второй корень
-Ребёнок второго корня
--Седьмая строка
---Восьмая строка