1

I have category hierarchy like this.

  • 721 parent is 235
  • 235 parent is 201
  • 201 parent is 1
  • 1 parent is 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

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

2
  • 2
    You’re not doing anything with the value returned from the recursive call of getPath. Commented Jun 8, 2012 at 20:38
  • Depending on your database, you may have extensions available for tree/graph data. Similarly, if you're going to be doing heavy work with your trees, a stored procedure may be of value to you. Commented Jun 8, 2012 at 20:59

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yes, you are right, I can't believe I missed that part. Thank you very much for your help here!
1

The line:

$this->getPath($parentId, $idList);

Needs to be

return $this->getPath($parentId, $idList);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.