Home  >  Article  >  Backend Development  >  Detailed explanation of return value of infinite classification recursive function in ecshop

Detailed explanation of return value of infinite classification recursive function in ecshop

伊谢尔伦
伊谢尔伦Original
2017-06-27 09:28:351573browse

When doing product classification in the secondary development of ecshopindex, the top-level category id must be obtained based on the category id. The first reaction was to use recursion to pass it out, so I wrote the recursive function as follows:

function getCatTopId($cat_id)
{
    if ($cat_id)
    {
      $res = Array();
        $sql = 'SELECT cat_id, parent_id'
             . ' FROM ' . $GLOBALS['ecs']->table('category') 
             . ' WHERE cat_id = ' . $cat_id . ' AND is_show = 1';
        $res = $GLOBALS['db']->getAll($sql);
        if ($res[0]['parent_id'] > 0)
        {
            getCatTopId($res[0]['parent_id']);
        }
        else
        {
            return $res[0]['cat_id'];
        }
    }
    else
    {
        return 1;
    }
}

A test program, no return value? After checking for a long time, no error was found. It seemed that the circuit in the brain was broken. When I asked Shui Shen (a kind-hearted netizen) today, he helped me answer it, and the modification is as follows:

function getCatTopId($cat_id)
{
    if ($cat_id)
    {
     $res = Array();
        $sql = 'SELECT cat_id, parent_id'
             . ' FROM ' . $GLOBALS['ecs']->table('category') 
             . ' WHERE cat_id = ' . $cat_id . ' AND is_show = 1';
        $res = $GLOBALS['db']->getAll($sql);
        if ($res[0]['parent_id'] > 0)
        {
            return getCatTopId($res[0]['parent_id']); // 修改处,多写个 return ,让函数返回值
        }
        else
        {
            return $res[0]['cat_id'];
        }    }
    else
    {
        return 1;
    }
}

The function is written internally. Even if it returns, it only returns to the position of the internal function, so there is still There is a main function, which must be returned again

The above is the detailed content of Detailed explanation of return value of infinite classification recursive function in ecshop. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn