如题,我的目的是想要统计无限分类中,父类下的所有子类的总数(包括孙类,重孙类...),在循环外显示正确了,但是在循环内不知道为什么显示错误.谁能帮忙解决下?十分感谢!//循环显示分类(部分代码)
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

解决方案 »

  1.   

    试试这样对不对:倒数第五行$countsort_number+=countSort($countsort_row['newssort_id']); 
      

  2.   

    $countsort_number 超级变量
    没有看到你将$countsort_number置0,一直无限的加下去.所以感觉有点问题.
      

  3.   

    在循環裏變量$countsort_number可能是沒有被初始化,你再調用的時候會在上一次的值再加下去
      

  4.   


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

  5.   


    我也感觉是这个问题,函数在while内没有被初始化,但是如何解决呢?
      

  6.   

    方法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;没有具体去验证,楼主自己试试吧
      

  7.   

    居然不能编辑发的贴,真烂。更正下:$countsort_number=0; 放到echo countSort($list_row['newssort_id']); //递归在while内显示错误,但在while外正常! 
    前面