loop and rename all subfolders in php

无人久伴 提交于 2019-12-13 23:53:05

问题


I'm struggling to find any information on looping through all subfolders within a folder and renaming them using PHP. I am renaming them so that I do not reach any limits on numbers of subfolders.

At the moment my user folder structure is as follows :

images/logos/1216/logo.jpg
images/logos/11437/logo.jpg
images/logos/234438/logo.jpg

So I want to loop through all folders within the 'logos' and rename them as follows :

images/users/1/1216/logos/logo.jpg
images/users/11/11437/logos/logo.jpg
images/users/234/234438/logos/logo.jpg

To calculate the new subfolder name, i'm going to take the existing user id (i.e. 11437 and divide by 1000).

The actual issue is how, do I loop through all the subfolders and what is the best way to rename the folder structure.


回答1:


If I'm correct about the first line of code here you sholud get an array lookin like the second line. Test that first and make a backup of your files.

This should list all userid's or directories and loop through them.
If the copy is success (true) it unlinks the old file, else returns a error message.

This is untested code

//$arr = array_filter(glob('images/logos/*'), 'is_dir');
$arr = array("images/logos/1216","images/logos/11437","images/logos/234438");
//var_dump($arr);

foreach($arr as $dir){
    $UID = str_replace("images/logos/", "", $dir);
    $newpath = "images/users/" . floor($UID/1000) . "/" . $UID . "/logos/logo.jpg";
    $oldpath = $dir . "/logo.jpg";
    if(copy($oldpath, $newpath)){
        unlink($oldpath);
    }else{
        echo "error with file " . $oldpath . "<br>\n";
        $error = true;
    }
}

if(!$error) unlink("images/logos");

EDIT; Just noticed I had used Excel too much lately. Changed the & to .
EDIT2; tested the code on my own page now and it seems the glob returns the path. Included code to get the UserID.



来源:https://stackoverflow.com/questions/45128852/loop-and-rename-all-subfolders-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!