递归函数不返回任何内容

时间:2021-04-30 13:13:11

标签: php recursion

我遇到了递归函数的问题,该函数必须在存储数据之前检查 db 表中是否已经使用了 id。如果是,则必须按 1000 次计时。如果仍在使用,则必须按 10 次等计时。

我知道我们应该在我们的数据库中使用主键,但这是公司政策。

这是我的代码:

function checkIdExits($id_conf, $world, $index = 0) {
    if ($index == 0) {
        if (checkIdDB($id_conf, $world) === true) {
            $id_conf = $id_conf * 1000;
            //echo "times 1000 $id_conf";
        } else {
            return $id_conf;
        }
    } else {
        $id_conf = $id_conf * 10;
        //echo "times 10 $id_conf";
    }
    if (checkIdDB($id_conf, $world) === true) {
        //echo "chek again $id_conf";
        checkIdExits($id_conf, $world, 1);
        
    } else {
      echo $id_conf;
        //return $id_conf;
        
    }    
}

checkIdDB 在数据库中执行查询,如果有行则正确返回 true,如果没有行则返回 false。

我在代码中输入的所有 echo 都表明该算法执行了正确的操作。 但是,只要它运行两次,return $id_conf; 行就不会返回任何内容。

我尝试使用 echo 而不是 return 并且这似乎有效。

有人能解释一下原因吗?

1 个答案:

答案 0 :(得分:2)

在递归调用函数时必须使用 return,否则中间结果将丢失。

if (checkIdDB($id_conf, $world) === true) {
    //echo "chek again $id_conf";
    return checkIdExits($id_conf, $world, 1);
}