【问题标题】:How to get files in a directory and save it in an array?如何获取目录中的文件并将其保存在数组中?
【发布时间】:2013-10-27 12:19:28
【问题描述】:

根据问题Is there an easy way to read filenames in a directory and add to an array?,我在一个目录中存储了不同的文件。现在我想获取 .jpg 文件并将其放入一个数组中,这样我就可以根据时间对数组进行排序并显示图像。我想获取文件名类似于

的 jpeg 文件

(日期在这里)-img_gen.jpg。 IE。 20131027123001-img-gen.jpg 20131030123102-img-gen.jpg

如何在 PHP 中做到这一点?谁能帮助我正确的分步代码来做到这一点?

我有这个代码,但它不适合我。

$ignore = array("..",".");
$dir = opendir("/home3/site/public_html/Master/uploader/uploader/");
$images = array();
$sortedimages = array();

//List files in images directory
while (($file = readdir($dir)) !== false)
    if (!in_array($file, $ignore))
        $images[] = $file;

foreach ($images as $image) {
    $filetime = filemtime("uploader/$image");
    $sortedimages[] = $filetime;
}

krsort($sortedimages);

foreach ($sortedimages as $sorted) {
    echo "$sorted<br/>";
}

closedir($dir);

它只是给我网关超时。所以我认为我真的需要一些比这更好的工作代码

请随时编辑我的代码或给我一些代码。在此先感谢:)

【问题讨论】:

  • 使用glob() 会更容易...see php docs
  • @charlietfl 感谢您的回答:) 你能给我一些关于如何使用 glob() 的示例代码吗?再次感谢
  • @ExpertSyStem 感谢您编辑我的代码。我试过了,但它返回错误 504 Gateway Timeout。你认为这里的问题是什么?谢谢
  • @JbenKaye 如果您还没有尝试过,请尝试我的代码。有用吗?
  • @JbenKaye:我没有编辑您的代码(从某种意义上说,我更改了任何内容以使其正常工作)。永远不应该这样做(他们应该发布答案)。我只是改进了它的格式,所以人们可以更容易地阅读它并发现可能的问题。 ComFreek 似乎知道它在说什么,所以试试它的建议并报告任何问题(如果有的话)。

标签: php arrays image


【解决方案1】:

使用glob()usort()

$dir = './';
$files = glob($dir . '*.jpg');

usort($files, function ($file1, $file2) use ($dir) {
  $f1 = filemtime($dir . $file1);
  $f2 = filemtime($dir . $file2);

  if ($f1 == $f2) {
    return 0;
  }
  return ($f1 < $f2) ? -1 : 1;
});

【讨论】:

  • 感谢@ComFreek。我试过了,但它没有显示我所做的任何东西 $dir = './upload/';你认为我们还能做些什么呢?再次感谢
  • 我按原样尝试了您的代码,但它没有显示任何内容。我也试过像 $dir = './uploader/upload';和 $dir = '/home3/site/public_html/Master/uploader/upload';但仍然没有显示任何内容?我究竟做错了什么?希望你能进一步帮助我。谢谢
  • @JbenKaye 为什么我的代码应该显示任何内容?它不使用echoprint。它只是为您准备一个排序的文件名数组。在我的代码 sn-p 之后,用$files 做任何你想做的事情。
  • 现在我意识到了。谢谢。我该如何测试它?我试图回显 $files 但它打印“数组”。谢谢。另外,我如何才能只整理名称为 20131030123102-img-gen.jpg 的文件?再次感谢您
  • @JbenKaye 试试var_dump($files),它将转储所有条目。您只想要具有这种文件名模式的文件吗?
猜你喜欢
  • 2013-01-07
  • 2018-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
  • 2016-10-21
相关资源
最近更新 更多