我很困惑:S用这个脚本...如果有一些文件,这个脚本工作,我会得到回声:
|test1.txt|test2.txt|test3.txt|test4.txt
问题是什么时候不存在任何文件,php会出错:
Warning: asort() expects parameter 1 to be array, null given in htdocs\test\ReadFolder8.php on line 6
Warning: Invalid argument supplied for foreach() in htdocs\test\ReadFolder8.php on line 8
可以创建一个查看是否有文件的函数,如果没有,可以获得“没有找到文件”的回音而没有错误?
<?php
$User = $_GET['User'];
foreach (glob("Myuser/$User/*.txt") as $path) {
$docs[$path] = filectime($path);
} asort($docs); // sort by value, preserving keys
foreach ($docs as $path => $timestamp) {
//print date("d M. Y:|H:i:s |", $timestamp);
print '|'. basename($path) .'' . "" . '';
}
?>
最后一件事,我不明白文件数据创建的顺序是如何工作的...如果我创建一个新文件,新文件将是最后一个字符串...我怎么能反转命令??
非常感谢:)
答案 0 :(得分:2)
解决方案很简单:在将变量$ docs用于这样的空变量之前,需要初始化它:
$docs = array(); // <-- create array $docs before use...
foreach (glob("Myuser/$User/*.txt") as $path) {
$docs[$path] = filectime($path);
}
asort($docs); // sort by value, preserving keys
要让函数输出错误消息,如果没有这样的文件,您可以使用count($docs)
简单地计算数组元素的数量,并检查它是否为0,如下所示:
if (count($docs) == 0) {
echo "no file found";
}
答案 1 :(得分:0)
您可以使用arsort()而不是asort()来获取最新文件。