限制按时间进行全局排序后的最大结果
我想限制在全局目录中的文件并按时间对它们进行排序后返回的结果。为了以防万一目录中没有文件,我还想包含一个 if file contains
短语。这是到目前为止的代码。
$list = glob('items/*.html');
usort(
$list,
create_function('$a,$b', 'return filemtime($a) < filemtime($b);')
);
foreach($list as $file)
{
include $file;
}
现在我猜测,我可能可以像这样执行 if (file_exists())
部分:
foreach($list as $file)
{
if (file_exists($file)) {
include $file;}
}
不会抛出错误,但是我在哪里可以最大计数到 5 或 7?
I'd like to limit the results returned after I glob the files in a directory and sort them by time. And just in case there are no files in the directory, I'd like to include an if file exists
phrase as well. Here is the code so far.
$list = glob('items/*.html');
usort(
$list,
create_function('$a,$b', 'return filemtime($a) < filemtime($b);')
);
foreach($list as $file)
{
include $file;
}
Now I'm guessing, I can probably do the if (file_exists())
part like this:
foreach($list as $file)
{
if (file_exists($file)) {
include $file;}
}
part without throwing errors, but where do I do the count up to a max of 5 or 7?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当目录中没有文件时,glob 返回一个空数组。这意味着, file_exists 是无用的,就像你有一个来自 glob 的值一样,它会存在。
如果 glob 因某种原因失败,它将返回 false。如果发生这种情况,您的脚本会抛出一些错误。尝试使用 is_array 在 foreach 之前检查数组。
glob returns an empty array when there are no files in the directory. This means, that an file_exists would be useless, as if you have an value from glob, it would exist.
If glob somehow fails, it will return false. You're script will throw some errors if this happens. Try checking for an array before the foreach using is_array.
这里实际上不需要执行
file_exists()
查询,因为如果glob
找到它,它就应该存在。不过,您可能想要执行is_read()
操作,在这种情况下,您可以像这样重写它:您可能还需要添加检查
glob
是否由于某种原因失败。There is not really a need to do a
file_exists()
query here, because ifglob
found it, it should exist. You might want to do anis_readable()
though, in this case you could rewrite it like this:You might also want to add a check if
glob
failed for some reason.尝试(最多包含 5 个文件)
try ( for max 5 file to include )