i'm trying to get a recursive function working in PHP but it fails with a "Fatal error: Allowed memory size of 134217728 bytes exhausted".
Why isn't this working?
$atest = array();
$atest = $this->resolveCategories(3,$atest);
var_dump($atest);
And the recursive function:
private function resolveCategories($iCategoryId,$aCategories){
$oCategory = CategoryQuery::create()->findOneById($iCategoryId);
if ($oCategory->getParentId() != null){
array_push($aCategories,$oCategory->getName());
$this->resolveCategories($iCategoryId,$aCategories);
}
return $aCategories;
}
4 Answers 4
I think you meant to call
$this->resolveCategories($oCategory->getParentId(), $aCategories);
inside, not
$this->resolveCategories($iCategoryId, $aCategories);
-
1Also, the whole polish notation thing is a bit old. Try meaningful name.
$category
and$categoryNames
reads a lot better.Sergiu Paraschiv– Sergiu Paraschiv2014年01月14日 19:39:43 +00:00Commented Jan 14, 2014 at 19:39
How does your function know when to stop? You are just calling the same function with the same parameters over and over. You created an infinite loop.
private function resolveCategories($iCategoryId,$aCategories){
// code...
$this->resolveCategories($iCategoryId,$aCategories);
// code...
}
You are never changing the $iCategoryId
parameter, so you just keep getting the same row (which happens to have a parent) over and over and over and over.
Perhaps you wanted:
$this->resolveCategories($iCategoryId-1, $aCategories);
or something?
For recursive functions , you always need a break statement which is generally a IF statement that will return false in on iteration. Generaly you can use a $depth variable and determinate how deep your recursive function can go!
-
i tried an else-part in my if clause. The break point should be if the actual element has no parentIdJ-H– J-H2014年01月14日 19:32:58 +00:00Commented Jan 14, 2014 at 19:32
-
getParentId() is supposed to return object right ? If so use is_object function and do not compare with NullAysennoussi– Aysennoussi2014年01月14日 19:33:50 +00:00Commented Jan 14, 2014 at 19:33
In general I don't understand how your algorithm is supposed to work. It seems like your array is going to recursively grow in size as you continue to pass the original array (plus item pushed to it to the recursive call.
-
The algorithm is supposed to add all category names to a array. it should end if the actual element has no more parents (parentId == null). Then it should return the generated array.J-H– J-H2014年01月14日 19:34:19 +00:00Commented Jan 14, 2014 at 19:34
$this->resolveCategories($iCategoryId,$aCategories);
Perhaps you wanted to do$this->resolveCategories($iCategoryId-1,$aCategories);
or something?