如何在文件名数组中使用rename()

时间:2015-12-05 21:28:34

标签: php

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";}

2 个答案:

答案 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的第一个键和值,因此$key0$fromFilenamemap.php然后使用密钥$fakeNames($ key)从0获取元素,即fake1.php。是重命名还是循环。

第二次迭代分别从$activeNames获取$key$fromFilename的第二个键和值,因此$key1$fromFilenametap.php然后使用密钥$fakeNames($ key)从1获取元素,即fake2.php。是重命名还是循环。

第三次迭代分别从$activeNames获取第三个键和值$key$fromFilename,因此$key2$fromFilenameapp.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;