3v4l.org

run code in 500+ PHP versions simultaneously
<?php $comments = [ [1, 1, 'Comment 1'], [2, 1, 'Comment 2'], [3, 2, 'Comment 3'], [4, 1, 'Comment 4'], [5, 2, 'Comment 5'], [6, 3, 'Comment 6'], [7, 7, 'Comment 7'], ]; $map = []; foreach($comments as $c) { $id = $c[0] === $c[1] ? 0 : $c[1]; $map[$id][] = $c; } function print_comments($arr, $depth) { global $map; foreach($arr as $c) { echo str_repeat("--", $depth) . "{$c[2]}\n"; print_comments($map[$c[0]] ?? [], $depth+1); } } print_comments($map[0], 0);

preferences:
50.76 ms | 1141 KiB | 5 Q