【问题标题】:Recursive function doesn't terminate on return递归函数不会在返回时终止
【发布时间】:2018-10-05 14:57:33
【问题描述】:
<?php
$sections = ['test', 'nesto', 'fo', 'bar', ['obama', 'tito']];

function search($sections, $query){
    $found = false;

    foreach ($sections as $section){
        if ($section == $query){
            $found = true;
            var_dump($found);
            return $found;
        }

        if (is_array($section)){
            search($section, $query);
        }
    }

    var_dump($found);

    return $found;
}

if (search($sections, 'obama')){
    echo 'search item found';
}else{
    echo 'nothing found';
}

我写了我的问题的简化版本。基本上我试图在嵌套数组中找到一个值。我得到以下输出: bool(true) bool(false) 没有找到。为什么找到的值会从真变为假。为什么 $section == $query 时函数没有终止?

【问题讨论】:

  • 您需要返回或设置在您的递归调用中找到。 return search($section, $query);
  • @ArtisticPhoenix 这么简单的答案,但我用我愚蠢的思维过程把它复杂化了。非常感谢!

标签: php recursion multidimensional-array


【解决方案1】:

试试这个

$sections = ['test', 'nesto', 'fo', 'bar', ['obama', 'tito']];

function search($sections, $query){
    $found = false;

    foreach ($sections as $section){
        if ($section == $query){
            $found = true;
            var_dump($found);
            return $found;
        }

        if (is_array($section)){
            return search($section, $query); //add return here
        }
    }

    var_dump($found);

    return $found;
}

if (search($sections, 'obama')){
    echo 'search item found';
}else{
    echo 'nothing found';
}

你必须返回递归调用的结果。

输出

bool(true)
search item found

Sandbox

你是这个[-] 关闭,大声笑。

你也可以这样做:

$found = search($section, $query);

并让函数末尾的 return 捕获它。你的选择。把它想象成一堆函数调用(因为它就是这样)。您必须通过堆栈返回结果,以便它可以从第一次调用(您的输出发生的地方)返回。

干杯!

【讨论】:

  • 感谢您的回复。答案很简单,但出于某种愚蠢的原因,我还没有真正考虑过,哈哈。干杯!
猜你喜欢
  • 1970-01-01
  • 2023-03-24
  • 2017-01-12
  • 2015-10-22
  • 2018-08-02
  • 2018-11-13
  • 1970-01-01
  • 2012-09-21
相关资源
最近更新 更多