recursion - php category recursive hierarchy -
i have category hierarchy this.
- 721 parent 235
- 235 parent 201
- 201 parent 1
- 1 parent 0
0 root category id, trying build function input leaf id 721, full path id of 721, 235, 201, 1
public function getpath($inputid = 0, $idlist=array()) { $sql ="select * hierarchy 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, when use function class, return null, $data = $whatevehelper->getpath('721');
could help?
thanks
you need change this:
if ($parentid !=0){ $this->getpath($parentid, $idlist); }
to this:
if ($parentid !=0){ return $this->getpath($parentid, $idlist); }
then need remove else clause , move "return $idlist;" line bottom of function returned. code above return $idlist in event $parentid 0. however, need function return if calling recursively.
i recommend along these lines whole function:
public function getpath($inputid = 0, $idlist=array()) { $sql ="select * hierarchy 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 works you.
Comments
Post a Comment