开发者

Problems trying to find the root category based on category id

I am trying to figure out the root level category_id of a category based on it's parent_id.

In the function below $this->cat_arr is an array of all categories and their parent_id's.

If a parent_id is set to 0 it is assumed to be a root node. I wish to loop through the array until I find the parent_id of passed $cat_id.

function getRoot($cat_id) {
    foreach ($this->cat_arr as $row) {
        if ($row->cat_id == $cat_id && $row->parent_id == 0) {
            return $row->cat_id;
            break;
        } else {
            $this->getRoot($row->parent_id);
        }
    }
}

In my application I only call this function when I know $cat_id is not at the root level (because the parent_id is greater than 0), but when I try to run this it gets stuck in an infinite loop.

Is my logic flawed, or am开发者_JAVA百科 I missing something simple?


Try this:

function getRoot($cat_id) {
    foreach ($this->cat_arr as $row) {
        if ($row->cat_id == $cat_id && $row->parent_id == 0) {
            return $row->cat_id;
        }
    }
    return $this->getRoot($row->parent_id);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜