Reputation: 3
so, this is weird, I have this method called treetrunk that runs up a parent child relationship and is supposed to return an array if ids as a "branchPath" - the method seems to be working just fine as a var_dump in my terminating condition shows the proper array. However if i try to call the method the returned array is "NULL" - I really dont get it..
Model method:
function treeTrunk($id){//1st id in is page id
if($id == '0'){
var_dump($this->branchPath); //this shows perfect array
return $this->branchPath; //this returns null
}
else{
$q = $this->getWhere(array('id'=>$id),null,null);
array_push($this->branchPath, $q[0]['pageParent']);
$this->treeTrunk($q[0]['pageParent']);
}
}
Calling via controller:
$d = $this->pages_mdl->treeTrunk('150');
var_dump($d); // <- this == NULL
var_dump from within method outputs "array(3) { [0]=> string(3) "148" [1]=> string(3) "146" [2]=> string(1) "0" } "
Upvotes: 0
Views: 1935
Reputation: 46900
That is supposed to be NULL
else{
$q = $this->getWhere(array('id'=>$id),null,null);
array_push($this->branchPath, $q[0]['pageParent']);
$this->treeTrunk($q[0]['pageParent']); // You have to return this value as well
}
When you don't return
that array, what else do you expect it to send back ? add a return
statement there. When you are dealing with recursion then your last call returned the value to your second last call, but did that call return it back to the original caller? so add a return
there
return $this->treeTrunk($q[0]['pageParent']);
And also remove the quotation marks around integer values, not only does it look bad, it sometimes stops working as expected in PHP then.
Upvotes: 0
Reputation: 30488
You are not returning anything in else
part.
else{
$q = $this->getWhere(array('id'=>$id),null,null);
array_push($this->branchPath, $q[0]['pageParent']);
$this->treeTrunk($q[0]['pageParent']);
}
should be
else{
$q = $this->getWhere(array('id'=>$id),null,null);
array_push($this->branchPath, $q[0]['pageParent']);
return $this->treeTrunk($q[0]['pageParent']);
}
As posted in you question you are passing 150
to treeTrunk()
function, so it goes to else part and gives you null
result. The if
part will evaluate when you pass 0
to treeTrunk()
function.
Upvotes: 1