【问题标题】:Recursive function not returning anything递归函数不返回任何内容
【发布时间】:2021-07-23 20:05:15
【问题描述】:

我遇到了一个递归函数的问题,它必须在存储数据之前检查 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,这似乎可行。

谁能解释一下原因?

【问题讨论】:

  • “递归函数不返回任何东西” - 你没有return...

标签: php recursion


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-08-23
    • 2014-04-18
    • 2016-02-15
    • 2012-11-27
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 2015-04-30
    相关资源
    最近更新 更多