问题
Wonder if you can help, i'm new to php and am stuck. I have loads of files that look like this:
2014-04-01 NS122345 - The date, the initials of the person and there employee code.
I want to be able to move the files that have NS or JB Or GA into there relevant folder/directories. So for NS it would go into the Nathan Saunders Folder, for JB into the Joe Bailey folder.
A few have said to me to use the explode and substr to split the filename up and then i guess search through the array. Someone said to use this:
$array = explode(' ', $filename);
$firstTwoLetters = string substr ($array[1], 0, 2);
But i get the error of variable filename not defined.
Unfortunately i have no clue. I have search through forums after forums and postings after postings, i have come up with this so far:
if(JFile::exists($searchpath .DS. '.doc')){
JFile::move($searchpath .DS. '.doc', JPATH_BASE .DS. 'upload' .DS. 'Nathan' .DS. '.doc'); }
My directory structure looks like this:
root/wan/upload - Where files/images/docs are stored. Inside upload folder i have:
>2014-04-08 NS6565.doc
>2012-01-03 JB8932.doc
>2013-02-01 GA5434.doc
>etc
root/wan/administrator/components/com_upload - where my code is stored
Problem is i have millions of these files, and the date at the start of the example i gave above will change for each.
I have tried putting them into an array but not sure from there how to then split/call the right one to put in the right folder:
Attempt - Array
$dir = JPATH_BASE . DS . "upload";
$basename = basename($dir);
$array = scandir($dir);
$filename = basename($dir[0]);
print_r($array);
print_r($basename);
Any help is much appreciated. Or if you can point me to examples/documentation that'll be great.
Thanks
回答1:
Assuming DS is DIRECTORY_SEPARATOR
$dir = JPATH_BASE . DS . "upload";
$folders = array('NS'=>'/path/to/Nathan/Saunders/Folder','JB'=>'/path/to/Joe/Bailey/folder');
$files = scandir($dir);
foreach($files AS $file){
if(!is_file($dir.DS.$file)){ continue; }
$array = explode(' ', $file);
if(count($array)<2){ continue; }
$firstTwoLetters = substr($array[1], 0, 2);
if(!empty($folders[$firstTwoLetters])){
rename($dir.DS.$file,$folders[$firstTwoLetters].DS.$file);
}
}
来源:https://stackoverflow.com/questions/26588225/php-exploding-moving-filename