douxie5930 2017-08-12 21:45
浏览 265
已采纳

PHP递归函数停止中循环

So every member has an intro_id, which stands for the userid of the guy who referred the member. If member 2 was referred by member 1, member 2s intro_id would be 1.

I am basically trying to "count" every ref, multiple levels deep. First level are direct referrals, second level are referrals referred by the first level refs.

Code so far:

function countReferrals($userid, $i){
    if($userid=='')
    {
       $userid=$_SESSION['member_id'];
    }
    if($i=='' || empty($i))
    {
       $i=0;
    }

    $query1 = new Bin_Query();
    $sql = "select member_id from members where intro_id='".$userid."'";
    $query1->executeQuery($sql);
    $level1Refs = $query1->records;

    foreach($level1Refs as $refer)
    {
       $i=$i+1;
       echo "<script>console.log( 'Debug Objects | countReferrals | \$i = ".$i." | \$refer[member_id] = ".$refer['member_id']."  ' );</script>";
       self::countReferrals($refer['member_id'], $i);
    }
}

This maximum output number ($i) is around 150. Sometimes 149, 146, ... First level referrals are 400+ and some in second level. So it's clearly stopping before it counts every ref, but why?

If I remove

self::countReferrals($refer['member_id'], $i);

It counts all level 1 refs. But I want refs from the other levels, too.

  • 写回答

1条回答 默认 最新

  • dongzhiyong8577 2017-08-12 21:55
    关注

    Your code runs in an endless loop (or at least until PHP cuts it off), because there is no restriction on when the recursive call is made. So when you see 149 or 150, it's likely because you have gone 148 or 149 levels deep and at the root function, you are still on the very first record.

    If you're interested only in n levels of depth, provide n as a parameter, and increment it every time you make a recursive call. In the function, check if n > $maxLevels return immediately.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?