PHP rename()
函数重命名文件,如
rename(oldname,newname)
但在我的情况下,我需要根据两个数组$activeNames
重命名批量文件,这两个数组是$fakeNames
数组的当前名称,它们是新名称。你能告诉我怎么做吗?
<?php
$dir = "data/";
$activeNames = ["map.php","tap.php","app.php"];
$fakeNames =["fake1.php","fake2.php","fake3.php"];
if(file_exists($dir."map.php")){
rename($dir."map.php", $dir."noha.php");
}
else {echo "File Name Already Changed";}
答案 0 :(得分:2)
$dir = "data/";
$activeNames = ["map.php","tap.php","app.php"];
$fakeNames =["fake1.php","fake2.php","fake3.php"];
创建2个数组,这两个数组都为每个元素设置了默认键....有效地它是
$activeNames = [0 => "map.php", 1 => "tap.php", 2 => "app.php"];
$fakeNames = [0 => "fake1.php", 1 => "fake2.php", 2 => "fake3.php"];
然后循环:
foreach($activeNames as $key => $fromFilename) {
$toFilename = $fakeNames[$key];
rename($dir . $fromFilename, $dir . $toFilename);
}
第一次迭代分别从$activeNames
获取$key
和$fromFilename
的第一个键和值,因此$key
为0
且$fromFilename
为map.php
然后使用密钥$fakeNames
($ key)从0
获取元素,即fake1.php
。是重命名还是循环。
第二次迭代分别从$activeNames
获取$key
和$fromFilename
的第二个键和值,因此$key
为1
且$fromFilename
为tap.php
然后使用密钥$fakeNames
($ key)从1
获取元素,即fake2.php
。是重命名还是循环。
第三次迭代分别从$activeNames
获取第三个键和值$key
和$fromFilename
,因此$key
为2
且$fromFilename
为app.php
然后使用密钥$fakeNames
($ key)从2
获取元素,即fake3.php
。重命名,并终止循环,因为它是最后一个条目。
答案 1 :(得分:1)
试试这个:
<?php
$dir = "data/";
$activeNames = ["map.php","tap.php","app.php"];
$fakeNames =["fake1.php","fake2.php","fake3.php"];
$errors = "";
for($i=0;$i<sizeof($activeNames);$i++){
if(file_exists($dir.$activeNames[$i])){
rename($dir.$activeNames[$i], $dir.$fakeNames[$i]);
}
else {$error.="File Name Already Changed\n";}
}
echo $errors;