所以我有一个处理CSV文件的应用程序。我有一行代码来加载这个文件。
$myFile = "data/FrontlineSMS_Message_Export_20120721.csv"; //The name of the CSV file
$fh = fopen($myFile, 'r'); //Open the file
我想找到一种方法,可以在data
目录中查找并获得最新的文件(它们都有日期标记,因此它们在data
中是有序的),并将名称设置为$myFile
。
我真的不能找到和理解php目录的文档,所以任何有用的资源也将不胜感激。谢谢。
发布于 2021-01-20 23:07:13
对于使用通配符的搜索,您可以使用:
<?php
$path = "/var/www/html/*";
$latest_ctime = 0;
$latest_filename = '';
$files = glob($path);
foreach($files as $file)
{
if (is_file($file) && filectime($file) > $latest_ctime)
{
$latest_ctime = filectime($file);
$latest_filename = $file;
}
}
return $latest_filename;
?>
发布于 2021-06-23 02:09:09
我的解决方案,来自Max Hofmann的改进解决方案:
$ret = [];
$dir = Yii::getAlias("@app") . "/web/uploads/problem-letters/{$this->id}"; // set directory in question
if(is_dir($dir)) {
$ret = array_diff(scandir($dir), array(".", "..")); // get all files in dir as array and remove . and .. from it
}
usort($ret, function ($a, $b) use ($dir) {
if(filectime($dir . "/" . $a) < filectime($dir . "/" . $b)) {
return -1;
} else if(filectime($dir . "/" . $a) == filectime($dir . "/" . $b)) {
return 0;
} else {
return 1;
}
}); // sort array by file creation time, older first
echo $ret[count($ret)-1]; // filename of last created file
发布于 2021-07-03 06:37:31
在下面的示例中,我更有信心使用自己的验证器,而不是简单地依赖于scandir()的时间戳。
在这种情况下,我想检查我的服务器是否有比客户端版本更新的文件版本。所以我比较了文件名中的版本号。
$clientAppVersion = "1.0.5";
$latestVersionFileName = "";
$directory = "../../download/updates/darwin/"
$arrayOfFiles = scandir($directory);
foreach ($arrayOfFiles as $file) {
if (is_file($directory . $file)) {
// Your custom code here... For example:
$serverFileVersion = getVersionNumberFromFileName($file);
if (isVersionNumberGreater($serverFileVersion, $clientAppVersion)) {
$latestVersionFileName = $file;
}
}
}
// function declarations in my php file (used in the forEach loop)
function getVersionNumberFromFileName($fileName) {
// extract the version number with regEx replacement
return preg_replace("/Finance D - Tenue de livres-darwin-(x64|arm64)-|\.zip/", "", $fileName);
}
function removeAllNonDigits($semanticVersionString) {
// use regex replacement to keep only numeric values in the semantic version string
return preg_replace("/\D+/", "", $semanticVersionString);
}
function isVersionNumberGreater($serverFileVersion, $clientFileVersion): bool {
// receives two semantic versions (1.0.4) and compares their numeric value (104)
// true when server version is greater than client version (105 > 104)
return removeAllNonDigits($serverFileVersion) > removeAllNonDigits($clientFileVersion);
}
使用这种手动比较而不是时间戳,我可以获得更外科手术的结果。如果你有类似的需求,我希望这能给你一些有用的想法。
(附言:我花了一些时间发表文章,因为我对我发现的与我的具体要求有关的答案不满意。请好心,我也不太习惯StackOverflow -谢谢!)
https://stackoverflow.com/questions/11597421
复制相似问题