<?php

$adjacencyList = array(
    array("id" => 1, "parentId" => null, "text" => "Первая строка"), 
    array("id" => 2, "parentId" => 3,    "text" => "Вторая строка"), 
    array("id" => 3, "parentId" => 1,    "text" => "Третья строка"),
    array("id" => 4, "parentId" => 1,    "text" => "Четвертая строка"),
    array("id" => 5, "parentId" => null, "text" => "Второй корень"), 
    array("id" => 6, "parentId" => 5, "text" => "Ребёнок второго корня"), 
    array("id" => 7, "parentId" => 6, "text" => "Седьмая строка"), 
    array("id" => 8, "parentId" => 7, "text" => "Восьмая строка"), 
);

function fillWithChildren(array $adjacencyList) {
    $nodesWithChildren = [];
    foreach ($adjacencyList as $node) {
       if (!array_key_exists($node['parentId'], $nodesWithChildren)) {
           $nodesWithChildren[$node['parentId']] = [];
       }
       $nodesWithChildren[$node['parentId']][] = $node;
    }
    return $nodesWithChildren;
}

function printList(array $nodes, $parentId = null, $depth = 0) {
   foreach ($nodes[$parentId] as $node) {
       visitNode($node, $depth);
       if (!empty($nodes[$node['id']])) {
           printList($nodes, $node['id'], $depth + 1);
       }           
   }
}

function visitNode(array $node, $depth) {
    echo str_repeat('-', $depth) . $node['text'] . PHP_EOL;
}

printList(fillWithChildren($adjacencyList));
