【问题标题】:Recursive Function returns null value递归函数返回空值
【发布时间】:2020-10-10 15:05:30
【问题描述】:

在递归函数下方,我正在尝试获取代码数组。例如输入'bme4',输出应该类似于[0]=>'bme'[1]=>'bm'[2]=>'b'。但是即使我可以使用 var_dump() 获得正确的返回值,返回值也是 null。

function get_parent_cat_code($code,$category_codes){
    $parent_cat_code=substr($code, 0, -1);
    if($parent_cat_code!=''){
        $category_codes[]=$parent_cat_code;
        get_parent_cat_code($parent_cat_code,$category_codes);
    }else{
        var_dump($category_codes);
        return $category_codes;
    }
}

【问题讨论】:

  • 在函数头中使用引用:function get_parent_cat_code($code, &$category_codes){}。提示:使用PSR-1 样式指南以获得更好的可读性代码。
  • 你这是什么意思?
  • 你不知道什么是引用吗?看看我在评论中放的代码。

标签: php arrays function recursion return


【解决方案1】:

解决了!

function get_parent_cat_code($code,$category_codes){
    $parent_cat_code=substr($code, 0, -1);
    if($parent_cat_code!=''){
        $category_codes[]=$parent_cat_code;
        return get_parent_cat_code($parent_cat_code,$category_codes); //i used return for calling recursive function.
    }else{
        var_dump($category_codes);
        return $category_codes;
    }
}

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 2012-03-11
    • 2017-05-14
    • 2021-08-14
    • 1970-01-01
    • 2014-07-13
    • 2017-09-24
    • 2021-03-02
    相关资源
    最近更新 更多