递归函数php中的返回
我对递归函数输出有点问题。代码如下:递归函数php中的返回,php,recursion,return,Php,Recursion,Return,我对递归函数输出有点问题。代码如下: 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[
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'];
}
问题是该函数在每次迭代时都会返回一个值,如下所示:
file.execategory/file.exe
root/category/file.exe 我只需要最后一个类似于完整路径的字符串。有什么建议吗 //UPD:完成,问题出在
$arr['text']=str_replace
中的点上
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']));
}
}
尝试一下:
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;
请试试这个。我知道它使用全局变量,但我认为这应该有效
$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);
什么是
$templates
-示例?@sashkello它肯定是一个递归函数,因为它会调用自身。如果您正在处理目录和文件,请查看RecursiveDirectoryIterator()@sash-一个调用自身的函数必须在术语recursive下。如果不使用全局函数,这段代码会更好。不需要它,而且它增加了不必要的复杂性。该函数输出相同的内容,但没有我需要的最后一个字符串。有一件事我想知道,$arr['parentId']!=0表示将在此处停止迭代?$arr['parentId']=0表示这是根文件夹;我们不需要更深入,函数开始替换文本。我的函数的结果相同,每次都返回iteration@bigbobr在我的示例中,$test
将保存整个字符串。该函数需要返回每个值才能递归使用。请更新您的问题,显示您在哪里使用该功能。它不应该在循环中使用,否则每次迭代都会覆盖$test
的值。我在代码中发现了问题,它是$arr['text']中的点。=感谢您的回复,它也起了作用;)谢谢您的评论:)您能将我的解决方案标记为有用的,这样它可能会帮助其他人吗