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

伊谢尔伦
Release: 2023-03-11 14:56:01
Original
1568 people have browsed it

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;
    }
}
Copy after login

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;
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!