[英]php category recursive hierarchy
我有這樣的類別層次結構。
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;
}
}
}
我可以在上面的var_dump部分看到正確的結果,但是當我從另一個類使用這個函數時,它返回null,就像這個$ data = $ whateveHelper-> getPath('721');
有人可以幫忙嗎?
謝謝
你只需要改變這個:
if ($parentId !=0){
$this->getPath($parentId, $idList);
}
對此:
if ($parentId !=0){
return $this->getPath($parentId, $idList);
}
然后你需要刪除else子句並移動“return $ idList;” 行到函數的底部,因此總是返回。 上面的代碼只會在$ parentId為0的情況下返回$ idList。但是,如果要以遞歸方式調用它,則需要該函數始終返回一些內容。
我建議您使用以下幾行來完成整個功能:
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;
}
如果這對您有用,請告訴我。
這條線:
$this->getPath($parentId, $idList);
需要是
return $this->getPath($parentId, $idList);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.