简体   繁体   English

php类递归层次结构

[英]php category recursive hierarchy

I have category hierarchy like this. 我有这样的类别层次结构。

  • 721 parent is 235 721父母是235
  • 235 parent is 201 235父母是201
  • 201 parent is 1 201父母是1
  • 1 parent is 0 1父母是0

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 0是根类别ID,我正在尝试构建一个输入叶ID为721的函数,获取721,235,201,1的完整路径ID

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'); 我可以在上面的var_dump部分看到正确的结果,但是当我从另一个类使用这个函数时,它返回null,就像这个$ 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;" 然后你需要删除else子句并移动“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. 上面的代码只会在$ parentId为0的情况下返回$ idList。但是,如果要以递归方式调用它,则需要该函数始终返回一些内容。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM