3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?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);
based on 4JuIa
Output for 7.0.0 - 7.2.0
Notice: Undefined index: parent in /in/q2ZeV on line 15 Array ( [1] => Array ( [content] => The first comment [parent] => 0 [comments] => Array ( [3] => Array ( [content] => Reply of first comment [parent] => 1 ) [4] => Array ( [content] => Another reply of first comemnt [parent] => 1 ) ) ) [2] => Array ( [content] => The second comment [parent] => 0 ) [4] => Array ( [comments] => Array ( [5] => Array ( [content] => Reply of a reply of the first comment [parent] => 4 ) ) ) )
Output for 5.4.0 - 5.6.28
Array ( [1] => Array ( [content] => The first comment [parent] => 0 [comments] => Array ( [3] => Array ( [content] => Reply of first comment [parent] => 1 ) [4] => Array ( [content] => Another reply of first comemnt [parent] => 1 ) ) ) [2] => Array ( [content] => The second comment [parent] => 0 ) [4] => Array ( [comments] => Array ( [5] => Array ( [content] => Reply of a reply of the first comment [parent] => 4 ) ) ) )
Output for 5.3.18 - 5.3.29
Parse error: syntax error, unexpected '[' in /in/q2ZeV on line 3
Process exited with code 255.