Per costruire strutture albero puoi scorrere i risultati e collegarli tramite riferimenti.
$tree = null; foreach ($results as $result) { $thisref = &$refs->{$result['id']}; if ($result['parentId'] == 0) { $tree->{$result['id']} = &$thisref; } else { $refs->{$result['parentId']}->children->{$result['id']} = &$thisref; } }L’output finale sarà un oggetto, non un array.