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.

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

报告相同问题?

悬赏问题

  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图