3v4l.org

run code in 300+ PHP versions simultaneously
<?php $resultset = [ ['id' => '1a', 'parent' => null], ['id' => '2a', 'parent' => null], ['id' => '3a', 'parent' => '1a'], ['id' => '4a', 'parent' => null], ['id' => '5a', 'parent' => '3a'], ['id' => '6a', 'parent' => '5a'], ['id' => '7a', 'parent' => null], ['id' => '8a', 'parent' => '3a'] ]; function findParent(&$array, $parent = 0, $children = []){ // make $array modifiable foreach ($array as $i => &$row) { // make $row modifiable if ($parent) { // if not zero if ($i == $parent) { // found parent unset($array[$i]['parent']); $row = $children; // append child to parent's children subarray } elseif (!empty($row)) { // go down rabbit hole looking for parent findParent($row, $parent, $children); // look deeper for parent while preserving the initial parent_id and row // $row = $row['children']; } // else continue; } elseif ($row['parent']) { // child requires adoption unset($array[$i]); // remove child from level because it will be store elsewhere and won't be its own parent (reduce iterations in next loop & avoid infinite recursion) findParent($array, $row['parent'], $row); // look for parent using parent_id while carrying the entire row as the childarray } // else continue; } return $array; // return the modified array } var_export(findParent($resultset));

preferences:
38.13 ms | 402 KiB | 5 Q