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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵