我编写了以下代码以查找添加到三个不同文件夹中的最新文件。我已将文件夹的目录存储在一个名为 path 的数组中。我还将最新文件的名称存储在另一个数组中。
$path[0] = "/Applications/MAMP/htdocs/php_test/check";
$path[1] = "/Applications/MAMP/htdocs/php_test/check2";
$path[2] = "/Applications/MAMP/htdocs/php_test/check3";
for ($i=0; $i<=2; $i++){
$path_last = $path[$i]; // set the path
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path_last);
while (false !== ($entry = $d->read())) {
$filepath = "{$path_last}/{$entry}";
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
$array[$i] = $latest_filename ; // assign the names of the latest files in an array.
}
}
一切正常,但现在我尝试将相同的代码放在一个函数中并在我的主脚本中调用它。我使用此代码来调用它:
include 'last_file.php'; // Include the function last_file
$last_file = last_file(); // assign to the function a variable and call the function
我不确定这是否正确。我想要做的是在我的主脚本中返回数组。我希望这里清楚我要解释的内容。感谢:D。
这是 last_file 函数:
function last_file(){
for ($i=0; $i<=2; $i++){
$path_last = $path[$i]; // set the path
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path_last);
while (false !== ($entry = $d->read())) {
$filepath = "{$path_last}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
$array[$i] = $latest_filename ; // assign the names of the latest files in an array.
}
}
return $array;
}//end loop
}//end function