How to create binary tree from array a recursive method?

I have a recursive function
function parseTree(&$tree, $root = null)
{
 $return = null;
 foreach ($tree as $key => &$item) {
 if ($root == null || $item['id'] == $root) {
 $return = [
 'person' => $item,
 'parents' => [
 'father' => parseTree($tree, $item['father_id']),
 'mother' => parseTree($tree, $item['mother_id'])
]
];
 unset ($tree[$key]);
}
}
 return $return;
}


that creates a binary tree, that is, from this array
array(
array(
 'name' => 'John',
 'id' => 1,
 'mother_id' => 2,
 'father_id' => 3
),
array(
 'name' => 'Lucy',
 'id' => 2,
 'mother_id' => 5,
 'father_id' => 4
),
array(
 'name' => 'Jim',
 'id' => 3,
 'mother_id' => 7,
 'father_id' => 9
),
array(
 'name' => 'Paul',
 'id' => 4,
 'mother_id' => 534,
 'father_id' => 54
),
array(
 'name' => 'Laura',
 'id' => 5,
 'mother_id' => 554,
 'father_id' => 51
),
array(
 'name' => 'Vanessa',
 'id' => 7,
 'mother_id' => 5354,
 'father_id' => 514
),
array(
 'name' => 'Adam',
 'id' => 9,
 'mother_id' => 245354,
 'father_id' => 514234
),
);


she's such an array

array(
array(
 'person' => array(
 'name' => 'John',
 'id' => 1,
 'mother_id' => 2,
 'father_id' => 3
),
 'parents' => array(
 'mother' => array(
 'person' => array(
 'name' => 'Lucy',
 'id' => 2,
 'mother_id' => 5,
 'father_id' => 4
),
 'parents' => array(
 'mother' => array(
 'person' => array(
 'name' => 'Laura',
 'id' => 5,
 'mother_id' => 554,
 'father_id' => 51
),
 'parents' => array(...)
),
 'father' => array(
 'person' => array(
 'name' => 'Paul',
 'id' => 4,
 'mother_id' => 534,
 'father_id' => 54
),
 'parents' => array(...)
 ), 
)
),
 'father' => ...
)


But when the array consists of more than 80 arrays the php script gives a time limit of 180. 180 seconds for such a small amount this is simply unacceptable. In General I need to modify somehow this feature to not work recursively, how can I do this? Maybe there are any articles on this subject?

PS: I'm using neo4j unfortunately it is not possible to return the data as a binary tree
July 9th 19 at 13:45

Find more questions by tags PHP