3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $items = array( (object) array('id' => 1, 'parent_id' => 0), (object) array('id' => 2, 'parent_id' => 0), (object) array('id' => 3, 'parent_id' => 0), (object) array('id' => 4, 'parent_id' => 1), (object) array('id' => 5, 'parent_id' => 1), (object) array('id' => 6, 'parent_id' => 2), ); function buildTree($items) { $childs = array(); foreach($items as $item) $childs[$item->parent_id][] = $item; foreach($items as $item) if (isset($childs[$item->id])) $item->childs = $childs[$item->id]; return $childs[0]; } $tree = buildTree($items); print_r($tree);
based on mR3oG
Output for 5.0.0 - 7.2.0
Array ( [0] => stdClass Object ( [id] => 1 [parent_id] => 0 [childs] => Array ( [0] => stdClass Object ( [id] => 4 [parent_id] => 1 ) [1] => stdClass Object ( [id] => 5 [parent_id] => 1 ) ) ) [1] => stdClass Object ( [id] => 2 [parent_id] => 0 [childs] => Array ( [0] => stdClass Object ( [id] => 6 [parent_id] => 2 ) ) ) [2] => stdClass Object ( [id] => 3 [parent_id] => 0 ) )
Output for 4.3.0 - 4.4.9
Array ( [0] => stdClass Object ( [id] => 1 [parent_id] => 0 ) [1] => stdClass Object ( [id] => 2 [parent_id] => 0 ) [2] => stdClass Object ( [id] => 3 [parent_id] => 0 ) )