PHP 递归函数返回值问题

vikinghetty 2009-08-17 05:49:25
如题,我的目的是想要统计无限分类中,父类下的所有子类的总数(包括孙类,重孙类...),在循环外显示正确了,但是在循环内不知道为什么显示错误.谁能帮忙解决下?十分感谢!

//循环显示分类(部分代码)
function listSort()
{
while($list_row = mysql_fetch_assoc($list_result))
{
echo countSort($list_row['newssort_id']); //递归在while内显示错误,但在while外正常!
}
}

//递归函数
function countSort($pid)
{
global $countsort_number;
$countsort_sql = "SELECT * FROM `{$db_table}newssort` WHERE `newssort_pid` = '$pid'";
$countsort_result = mysql_query($countsort_sql) or die('数据库查询失败,请与管理员联系!');
$num = mysql_num_rows($countsort_result);
$countsort_number += $num;
if($num > 0)
{
while($countsort_row = mysql_fetch_assoc($countsort_result))
{
countSort($countsort_row['newssort_id']);
}
}
return $countsort_number;
}

参考图片:http://hiphotos.baidu.com/forhaha/abpic/item/dccc48efd5b09cfeb21cb10c.jpg
...全文
1122 12 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
vikinghetty 2009-08-19
  • 打赏
  • 举报
回复
唉...无解吗?结帖了,分数分给参与回答的人...
xuzuning 2009-08-18
  • 打赏
  • 举报
回复
请给出完整的代码,至少函数内的代码不能缩减
想你的我们 2009-08-18
  • 打赏
  • 举报
回复
居然不能编辑发的贴,真烂。

更正下:

$countsort_number=0; 放到echo countSort($list_row['newssort_id']); //递归在while内显示错误,但在while外正常!
前面
想你的我们 2009-08-18
  • 打赏
  • 举报
回复
方法1:global $countsort_number; 改成 $countsort_number=0;

countSort($countsort_row['newssort_id']); 改成 $countsort_number += countSort($countsort_row['newssort_id']);

原因是你global的话,$countsort_number就纠缠不清了。

方法2:
echo countSort($list_row['newssort_id']); //递归在while内显示错误,但在while外正常!
这句后面加上$countsort_number=0;

没有具体去验证,楼主自己试试吧
YHL27 2009-08-17
  • 打赏
  • 举报
回复
sf!!!
tfxg 2009-08-17
  • 打赏
  • 举报
回复
在循環裏變量$countsort_number可能是沒有被初始化,你再調用的時候會在上一次的值再加下去
程序猿之殇 2009-08-17
  • 打赏
  • 举报
回复
$countsort_number 超级变量
没有看到你将$countsort_number置0,一直无限的加下去.所以感觉有点问题.
阿_布 2009-08-17
  • 打赏
  • 举报
回复
试试这样对不对:倒数第五行

$countsort_number+=countSort($countsort_row['newssort_id']);
dzxccsu 2009-08-17
  • 打赏
  • 举报
回复
看你的两个函数都没错误,具体报的什么错误呢?
vikinghetty 2009-08-17
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 jakey9826 的回复:]
$countsort_number 超级变量
没有看到你将$countsort_number置0,一直无限的加下去.所以感觉有点问题.
[/Quote]

我也感觉是这个问题,函数在while内没有被初始化,但是如何解决呢?
vikinghetty 2009-08-17
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 zhoupuyue 的回复:]
试试这样对不对:倒数第五行
PHP code$countsort_number+=countSort($countsort_row['newssort_id']);
[/Quote]

还是不行...
vikinghetty 2009-08-17
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 dzxccsu 的回复:]
看你的两个函数都没错误,具体报的什么错误呢?
[/Quote]

没有报错,就是显示不正确.但在while循环外显示是正确的.

21,893

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧