Home  >  Article  >  php教程  >  PHP中递归函数返回值使用介绍(ecshop无限分类)

PHP中递归函数返回值使用介绍(ecshop无限分类)

WBOY
WBOYOriginal
2016-06-13 10:01:271213browse

一款以ecshop无限分类为实例来介绍一下php中的递归函数返回值的问题介绍。

在 ecshop 二次开发中做产品分类索引时,要根据分类 id 取得所属顶级分类 id 。第一个反应就是用递归递出来,于是写了递归函数如下:

 代码如下 复制代码

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;
    }
}

 

一测试程序,没有得到返回值?检查了很久都没有发现错误,看来脑壳断路了。今天问水神(一好心网友)时,他帮我解答出来了,修改如下:

 代码如下 复制代码

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;
    }
}

 

函数写在内部,就算返回了,也只是返回到内部的那个函数的位置,所以外面还有一层主函数,必须再 return 一下

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