Ivan Ivan - 1 month ago 14
PHP Question

Recursive looping return 500 Internal Server Error

Am geting 500 Internal server error when recursive is called in loop! Only than i get 500 error.

When i remove recusive in loop everything work good:

Check my code:

public function getRecrusiveReferals($userID)
{
$sql = "SELECT user_id, username, refered_by FROM users WHERE refered_by = ?";

$referals = $this->db->query($sql, $userID);

$list = $this->buildReferalsTree($referals->result_array());

return $list;
}


private function buildReferalsTree(array $referals, $parentID = 0)
{
$data = array();

foreach ($referals as $item)
{
if($item['refered_by'])
{
$children = $this->buildReferalsTree($referals, $parentID);

if($children) {
$item['children'] = array();
}

}
$data[] = $item;

}

return $data;
}

Answer

As Jay Rajput said, you've got infinite recursion there. I think that the call

$children = $this->buildReferalsTree($referals, $parentID);

should pass not the $referals, but another array, built based on 'refered_by' element of $item. So basically you need to create another private method, that extracts new $referals. You must be still aware that this code won't be errorprone, and if two items refer each other you will still end with an infinite recursion.

What you're trying to accomplish is quite a challenge, especially when you're using relational database. You definitely would like to look at the 'nested set' concept in relational databases.

Comments