3v4l.org

run code in 300+ PHP versions simultaneously
<?php $comments = [ 1 => ['content' => "The first comment", 'parent' => 0], 2 => ['content' => "The second comment", 'parent' => 0], 3 => ['content' => "Reply of first comment", 'parent' => 1], 4 => ['content' => "Another reply of first comemnt", 'parent' => 1], 5 => ['content' => "Reply of a reply of the first comment", 'parent' => 4] ]; foreach($comments as $id => &$value) { # check if there is a parent if ($parentId = $value['parent']) { $comments[$parentId]['comments'][$id] =& $value; # add child to parent unset($comments[$id]); # remove reference from topmost level } } unset($value); # remove iterator reference print_r($comments); # your tree // foreach($comments as $id => &$c) { // if (isset($comments[$c['parent']])) { // $comments[$c['parent']]['comments'][$id] =& $c; // unset($comments[$id]); // } // } // var_dump($comments);

preferences:
49.96 ms | 402 KiB | 5 Q