在PHP问题中将350K元素数组转换为Tree结构

Hi I have following array:

Huge_Array (356362 elements) //used splfixedarray for better handling of this array
(
    [1] => 0
    [2] => 1
    [3] => 2
    [4] => 3
    [5] => 1
    [6] => 0
)

keys of this array is unique, and values showing parent of key. like parent of 1 & 6 is 0, parent of 2 is 1, for 3 is 2....

This array is grabbing the id and parent id of a node, these node's in the table are self referencing i.e id: 234 parentid: 345 , id:345 parentid:676. Im trying to create a tree out of these nodes, the array is created and holds the relationships of child, parent properly. However it only works for a certain limit of nodes like a couple thousand . the complete tree is suppose to be made out of an array with 350k nodes which I already have. I serialized it and get the file contents (file size 7mb), now with that array (unserlized successfully) I do the following to create the tree. This however doesn't work for a huge array though. It times out because its too large but it works for smaller arrays. What I'm I doing wrong and how can I make this support the huge array and contruct the tree in memory?

class node {

    var $children;


    public function __construct(){
        $this->children = array();

    }

}

$tree = array();

foreach ($Huge_array as $q => $p){

    if(!isset($tree[$p]))
        $tree[$p] = new node;
    if(!isset($tree[$q]))
        $tree[$q] = new node;

    $mark[$p]=FALSE;
    $mark[$q]=FALSE;
    array_push($tree[$p]->children,$q);

}
var_dump($tree);