我构建了一个带有文件名的函数,并在文件名中递增一个计数器并返回它,但是,一切都是正确的,除了return不返回文件名。
请帮忙吗?
我的代码:
$filename = join("", array_reverse($date));
$filename .= ".xml";
$dir = "../gigs";
$file = $dir."/".$filename;
function getNewFileName($filename, $dir) {
if (is_file("$dir/$filename")) {
if (strpos($filename, "_") === false) {
$filename = str_replace(".xml","_1.xml",$filename);
getNewFileName($filename, $dir);
}
else {
$pos = strpos($filename, "_");
$counter = (int)substr($filename, $pos+1,1);
$counter++;
$filename = substr($filename,0, $pos)."_".$counter.".xml";
getNewFileName($filename, $dir);
}
} else {
// echoing HERE shows that the string is manipulated correctly
return (string)$filename; // but returning here is not working
}
}
echo getNewFileName($filename, $dir); // <- this last line prints nothing out
提前致谢。
答案 0 :(得分:11)
该行:
getNewFileName($filename, $dir);
需要return
:
return getNewFileName($filename, $dir);
答案 1 :(得分:1)
这是你的功能应该是这样的:
function getNewFileName($filename, $dir) {
if (is_file("$dir/$filename")) {
if (strpos($filename, "_") === false) {
$filename = str_replace(".xml","_1.xml",$filename);
return getNewFileName($filename, $dir);
}
else {
$pos = strpos($filename, "_");
$counter = (int)substr($filename, $pos+1,1);
$counter++;
$filename = substr($filename,0, $pos)."_".$counter.".xml";
return getNewFileName($filename, $dir);
}
}
return (string)$filename;
}
echo getNewFileName($filename, $dir); // <- this last line prints nothing out
答案 2 :(得分:0)
首先,请尝试格式化代码,以便缩进可读。其次,你只是没有从递归调用返回到getNewFileName()
:
function getNewFileName($filename, $dir) {
if (is_file("$dir/$filename")) {
if (strpos($filename, "_") === false) {
$filename = str_replace(".xml","_1.xml",$filename);
return getNewFileName($filename, $dir); // here
} else {
$pos = strpos($filename, "_");
$counter = (int)substr($filename, $pos+1,1);
$counter++;
$filename = substr($filename,0, $pos)."_".$counter.".xml";
return getNewFileName($filename, $dir); // and here
}
} else {
return (string)$filename;
}
}
假设这是你的意图。
答案 3 :(得分:-1)
function getNewFileName($filename, $dir) {
if (is_file("$dir/$filename")) {
if (strpos($filename, "_") === false) {
$filename = str_replace(".xml","_1.xml",$filename);
return (string)$filename;
} else {
$pos = strpos($filename, "_");
$counter = (int)substr($filename, $pos+1,1);
$counter++;
$filename = substr($filename,0, $pos)."_".$counter.".xml";
return (string)$filename;
}
} else {
return (string)$filename;
}
}
你的函数有一个循环到无穷大。