I have category hierarchy like this.
0 is the root category id, I am trying to build a function that input leaf id 721, get full path id of 721, 235, 201, 1
public function getPath($inputId = 0, $idList=array())
{
$sql ="SELECT * FROM hierarchy where id='{$inputId}'";
$result = $this->db->fetchAll($sql);
if($result){
$currentId = $result[0]["id"];
$parentId = $result[0]["parent_id"];
$idList[] = $currentId;
if ($parentId !=0){
$this->getPath($parentId, $idList);
}else{
//var_dump($idList);
return $idList;
}
}
}
I can see correct results in var_dump part above, but when I use this function from another class, it return null, like this $data = $whateveHelper->getPath('721');
could anyone help?
Thanks
You just need to change this:
if ($parentId !=0){
$this->getPath($parentId, $idList);
}
to this:
if ($parentId !=0){
return $this->getPath($parentId, $idList);
}
Then you need to remove the else clause and move the "return $idList;" line to the bottom of your function so it is always returned. Your code above would only return $idList in the event that the $parentId was 0. However, you need the function to always return something if you are calling it recursively.
I recommend something along these lines for your whole function:
public function getPath($inputId = 0, $idList=array())
{
$sql ="SELECT * FROM hierarchy where id='{$inputId}'";
$result = $this->db->fetchAll($sql);
if($result){
$currentId = $result[0]["id"];
$parentId = $result[0]["parent_id"];
$idList[] = $currentId;
if ($parentId !=0){
return $this->getPath($parentId, $idList);
}
}
return $idList;
}
Let me know if that works for you.
The line:
$this->getPath($parentId, $idList);
Needs to be
return $this->getPath($parentId, $idList);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.