【发布时间】:2023-12-11 05:45:02
【问题描述】:
假设有一个名为“abc”的目录
此目录包含许多文件。在所有这些文件中,我只想要 php 中的数组中最新的“X”或最新的 15 个文件(如果可能,使用 glob 函数)。
每一个帮助都会非常显着。
【问题讨论】:
-
你有没有尝试过?
-
感谢大家宝贵的时间和帮助。不过,我自己试了,也得到了答案,我就把它作为答案贴出来
假设有一个名为“abc”的目录
此目录包含许多文件。在所有这些文件中,我只想要 php 中的数组中最新的“X”或最新的 15 个文件(如果可能,使用 glob 函数)。
每一个帮助都会非常显着。
【问题讨论】:
// directory for searching files
$dir = "/etc/php5/*";
// getting files with specified four extensions in $files
$files = glob($dir."*.{extension1,extension2,extension3,extension4}", GLOB_BRACE);
// will get filename and filetime in $files
$files = array_combine($files, array_map("filemtime", $files));
// will sort files according to the values, that is "filetime"
arsort($files);
// we don't require time for now, so will get only filenames(which are as keys of array)
$files = array_keys($files);
$starting_index = 0;
$limit = 15;
// will limit the resulted array as per our requirement
$files = array_slice($files, $starting_index,$limit);
// will print the final array
echo "Latest $limit files are as below : ";
print_r($files);
如果我错了,请改进我
【讨论】:
使用此处发布的功能:http://code.tutsplus.com/tutorials/quick-tip-loop-through-folders-with-phps-glob--net-11274
$dir = "/etc/php5/*";
// Open a known directory, and proceed to read its contents
foreach(glob($dir) as $file)
{
echo "filename: $file : filetype: " . filetype($file) . "<br />";
}
并在 foreach 循环中使用 filetime() 函数作为 IF 语句。:http://php.net/manual/en/function.filemtime.php
【讨论】:
一种比 glob 更好的方法是使用RecursiveDirectoryIterator
$dir = new \RecursiveDirectoryIterator('path/to/folder', \FilesystemIterator::SKIP_DOTS);
$it = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::SELF_FIRST);
$it->setMaxDepth(99); // search for other folders and they child folders
$files = [];
foreach ($it as $file) {
if ($file->isFile()) {
var_dump($file);
}
}
或者如果你仍然想用 glob 来做
$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
var_dump($file);
}
【讨论】: