3v4l.org

run code in 300+ PHP versions simultaneously
<?php $arr = [ ['comment_id' => 32, 'article_id' => 5, 'parent_id' => 31, 'user_id' => 22, 'content' => 'dolor sit amet consectetur adipisicing', 'created_at' => '02-04-2021'], ['comment_id' => 30, 'article_id' => 5, 'parent_id' => 29, 'user_id' => 22, 'content' => 'Lorem ipsum dolor sit amet.', 'created_at' => '01-04-2021'], ['comment_id' => 31, 'article_id' => 5, 'parent_id' => 29, 'user_id' => 22, 'content' => 'Sit amet consectetur adipisicing', 'created_at' => '02-04-2021'], ['comment_id' => 29, 'article_id' => 5, 'parent_id' => 0, 'user_id' => 22, 'content' => 'dolor sit amet consectetur adipisicing', 'created_at' => '01-04-2021'] ]; $arr_by_comment_id = array_column($arr, null, 'comment_id'); $root_entry = null; foreach ($arr_by_comment_id as &$entry) { if ($entry['parent_id'] === 0) { $root_entry =& $entry; } elseif (array_key_exists($entry['parent_id'], $arr_by_comment_id)) { $arr_by_comment_id[$entry['parent_id']]['comments'][] = $entry; } } unset($entry); // For safety (after reference looping) print_r($root_entry);

preferences:
138.6 ms | 405 KiB | 5 Q