function test($a, $b){ 
    $arr = [$a, $b]; 
 
    if($a == 1){ 
        echo "first here"; 
        test(3,4); 
    } 
    else{ 
        echo "second here"; 
        return [$a, $b]; 
    } 
    echo "should have returned earlier"; 
    return $arr; 
} 
 
$arr = test(1,2); 
print_r($arr); 

我期待 [0 => 3, 1 => 4] 但收到 [0 => 1,1 => 2]

谁能解释一下它是如何返回的?

请您参考如下方法:

当你处理递归时,你应该返回一个递归函数。

function test($a, $b){ 
    $arr = [$a, $b]; 
 
    if ($a === 1) { 
        echo "first here"; 
        return test(3,4); 
    } 
    // ELSE is not needed as if $a === 1 the program will never get here 
    echo "second here"; 
    return [$a, $b]; 
} 
 
$arr = test(1,2); 
print_r($arr); 

请考虑通过精确指定所需的输出和行为来更新您的问题。如果我为您创建的代码是您想要的结果,您还应该考虑更改您的代码,因为它不是动态的并且可能没有用例。


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!