To solve your problem you need to properly understand how variable referencing/aliasing in PHP works.
Look at the following example code, which does not look much different to yours but makes use of references in order to access any parent even it has already “moved”:
# transform $flat into a tree:
foreach($flat as $id => &$value)
{
# check if there is a parent
if ($parentId = $value['parent'])
{
$flat[$parentId][0][$id] =& $value; # add child to parent
unset($flat[$id]); # remove reference from topmost level
}
}
unset($value); # remove iterator reference
print_r($flat); # your tree
$flat
now contains all values from $flat
– but reordered. Demo.