3v4l.org

run code in 300+ PHP versions simultaneously
<?php function replaceParent(&$array, $parent = null) { foreach ($array as &$item) { if ($item['id'] == $parent) { if ($item['parent']) { return replaceParent($array, $item['parent']); } else { return $item['id']; } } elseif ($item['parent']) { $item['parent'] = replaceParent($array, $item['parent']); } } } $array = [ '0' => [ 'id' => 1, 'parent' => 0, 'name' => 'root 0' ], '1' => [ 'id' => 2, 'parent' => 1, 'name' => 'root 1' ], '2' => [ 'id' => 3, 'parent' => 2, 'name' => 'root 2' ], '3' => [ 'id' => 4, 'parent' => 3, 'name' => 'root 3' ], '4' => [ 'id' => 5, 'parent' => 3, 'name' => 'root 4' ], '5' => [ 'id' => 6, 'parent' => 2, 'name' => 'root 2' ] ]; replaceParent($array); var_export($array);

preferences:
25.75 ms | 404 KiB | 5 Q