【问题标题】:Return in recursive function php返回递归函数php
【发布时间】:2013-09-21 20:36:37
【问题描述】:

递归函数输出有点问题。代码如下:

function getTemplate($id) {
    global $templates;
    $arr = $templates[$id-1];
    if($arr['parentId'] != 0) {
        $arr['text'] .= str_replace($arr['attr'], $arr['text'], getTemplate($arr['parentId']));
    }
    return $arr['text']; 
}

问题在于该函数在每次迭代时都会返回一个值,如下所示:

文件.exe
类别/file.exe
根目录/类别/file.exe

我只需要最后一个类似于完整路径的字符串。有什么建议吗?

//UPD:完成,问题出在$arr['text'] .= str_replace中的点

【问题讨论】:

  • 什么是$templates - 示例?
  • @sashkello 它肯定是一个递归函数,因为它会调用自己。
  • 如果您正在处理目录和文件,请查看 RecursiveDirectoryIterator() php.net/manual/es/class.recursivedirectoryiterator.php
  • @sash - 调用自身的函数必须在术语递归下
  • 这段代码如果不使用全局代码会更好很多。没有必要,它增加了不必要的复杂性。

标签: php recursion return


【解决方案1】:

请试试这个。我知道它使用全局变量,但我认为这应该可行

$arrGlobal = array();

function getTemplate($id) {
    global $templates;
    global $arrGlobal;

    $arr = $templates[$id-1];
    if($arr['parentId'] != 0) {
       array_push($arrGlobal, getTemplate($arr['parentId']));
    }
    return $arr['text'];
}

$arrGlobal = array_reverse($arrGlobal);

echo implode('/',$arrGlobal);  

【讨论】:

  • 我在我的代码中发现了问题,它是 $arr['text'] 中的点。=感谢您的回复,它也有效;)
  • 感谢您的评论 :) 您能否将我的解决方案标记为有用,以便对其他人有所帮助
【解决方案2】:

试试这个,

function getTemplate($id) {
    global $templates;
    $arr = $templates[$id-1];
    if($arr['parentId'] != 0) {
    return $arr['text'] .= str_replace($arr['attr'], $arr['text'], getTemplate($arr['parentId']));
    }
}

【讨论】:

  • 该函数输出相同的内容,但没有我需要的最后一个字符串。
  • 我想知道一件事,$arr['parentId'] != 0 是否意味着它会在这里停止迭代?
  • $arr['parentId']=0 表示这是根文件夹;我们不需要更深入,函数开始替换文本。
【解决方案3】:

试试看:

function getTemplate($id, array $templates = array())
{
  $index = $id - 1;
  if (isset($templates[$index])) {
    $template = $templates[$index];
    if (isset($template['parentId']) && $template['parentId'] != 0) {
      $parent = getTemplate($template['parentId'], $templates);
      $template['text'] .= str_replace($template['attr'], $template['text'], $parent);
    }
    return $template['text'];
  }
  return '';
}

$test = getTemplate(123, $templates);

echo $test;

【讨论】:

  • 我的函数结果相同,每次迭代都返回
  • @bigbobr 在我的示例中,$test 将保存整个字符串。该函数需要返回每个值才能递归使用。请更新您的问题,显示您在哪里使用该功能。不应在循环中使用它,否则您将在每次迭代时覆盖 $test 的值。
猜你喜欢
  • 2012-03-11
  • 2015-04-27
  • 2018-01-04
  • 2011-05-23
  • 2021-03-02
  • 2021-08-14
  • 2018-02-21
  • 2020-09-05
  • 2022-01-16
相关资源
最近更新 更多