【发布时间】:2016-04-02 22:51:25
【问题描述】:
好的,我不完全理解我在这里做什么,所以我想我会得到一些关于我的代码的反馈。
尝试递归搜索我服务器上的特定文件夹,并返回最新添加的 30 个 *.jpg 图像(带有完整文件路径)。
目前,我当前的代码给了我(我假设)时间戳(它们每个看起来都像一串 10 个数字),实际上我似乎只得到了我期望的全部 30 个中的 22 个。我看到另一篇使用 directoryIteratorIterator 的帖子,但我无法为我的服务器升级我的 PHP 版本,也找不到很多明确的文档。
希望有人能在这方面引导我朝着正确的方向前进。
<?php
function get30Latest(){
$files = array();
foreach (glob("*/*.jpg") as $filename) { //I assume "*/*.jpg" would start from the root of the server and go through each directory looking for a match to *.jpg and add to $files array
$files[$filename] = filemtime($filename);
}
arsort($files); //I may not need this since I'm looking to sort by earliest to latest (among the 30 newest images)
$newest = array_slice($files, 0, 29); //This should be the first 30 I believe.
foreach ($newest as $file){ //Assuming I would loop through the array and display the full paths of these 30 images
echo $file . "</br>"; //Returns something similar to "1451186291, 1451186290, 1451186290, etc..."
}
}
?>
【问题讨论】:
-
递归目录迭代器从
PHP v5开始,所以除非你有v4.x,否则你可以使用该方法:php.net/manual/en/class.recursivedirectoryiterator.php 该页面上的第一个贡献者注释可能是你需要进行迭代和jpg的正则表达式。 -
好的,尝试了第一个贡献者的笔记。工作,所以我想我至少有 v5 PHP。事情进展顺利,但是我只看到打印了“数组”,而不是文件路径。这是我目前所处的位置:
function get30Latest(){ $directory = new RecursiveDirectoryIterator('./'); $iterator = new RecursiveIteratorIterator($directory); $regex = new RegexIterator($iterator, '/^.+\.jpg$/i', RecursiveRegexIterator::GET_MATCH); $count = 1; foreach($regex as $file){ echo $count . ":" . " " . $file . "</br>"; $count++; } } -
那么你看到每个文件的路径了吗?喜欢
/server/root/html/webroot/images/file.jpg? -
不,我看到“1:数组,2:数组,3:数组....”
-
哦,是的,我明白了,这会保存到一个数组中,所以在你的情况下:
echo $count . ":" . " " . $file[0] . "</br>";
标签: php file recursion directory