An introduction to the problem of returning values of recursive functions in PHP using ecshop infinite classification as an example.
When doing product category indexing in the secondary development of ecshop, the top-level category id must be obtained based on the category id. The first reaction was to use recursion, so I wrote the recursive function as follows:
The code 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)
{
getCatTopId($res[0]['parent_id']);
}
else
{
return $res[0]['cat_id'];
}
}
else
{
return 1;
}
}
|
|
Copy code
|
代码如下 |
复制代码 |
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;
}
}
|
function getCatTopId($cat_id)
{
If ($cat_id)
{
$res = Array();
$sql = 'SELECT cat_id, parent_id'
. ' FROM ' . $GLOBALS['ecs']->table('category')
. .
$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, but no return value is obtained? After checking for a long time, no error was found. It seemed that the circuit in the brain was broken. When I asked the Water God (a kind-hearted netizen) today, he helped me answer it, and the modification is as follows:
The code is as follows
|
Copy code
|
function getCatTopId($cat_id)
{
If ($cat_id)
{
$res = Array();
$sql = 'SELECT cat_id, parent_id'
. ' FROM ' . $GLOBALS['ecs']->table('category')
. .
$res = $GLOBALS['db']->getAll($sql);
if ($res[0]['parent_id'] > 0)
{
return getCatTopId($res[0]['parent_id']); // Modify, write more return to let the function return the value
}
else
{
return $res[0]['cat_id'];
} } }
else
{
Return 1;
}
}
The function is written internally. Even if it returns, it will only return to the position of the internal function, so there is another main function outside, and it must be returned again
http://www.bkjia.com/PHPjc/631608.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631608.htmlTechArticleAn introduction to the problem of returning values of recursive functions in PHP using ecshop infinite classification as an example. When doing product category indexing in the secondary development of ecshop, you need to obtain the category according to the category id...
|