【问题标题】:Sort Images in while loop (no mysqli)在while循环中对图像进行排序(没有mysqli)
【发布时间】:2016-03-06 18:56:42
【问题描述】:

我想从目录中的几个子文件夹中获取图片,并将它们作为数据进行排序。使用以下代码,我得到了图像,现在我想将它们作为数据进行排序。

注意

每个图片名称都以上传示例的日期和时间开头:-

默认图片名称 = "image.jpg"

上传后图片名称=“24-02-2016-09-42-33-image.jpg

<?php
    $dir = 'dist/userdata/'.$username.'/photos/';

    if ($opendir = opendir ($dir) ) {

      $files = 0;

      while (($file = readdir ($opendir)) !== false && $files <= 2 + 1 ) {

        if ($file !="." && $file !="..") {

          $newdir = $dir.''.$file.'/';

          if ($newopendir = opendir ($newdir)) {
            $imgs = 0;
            while (($img = readdir ($newopendir)) !== false && $imgs <= 3 + 1) {
              if ($img !=="." && $img !=="..") {

                $supported_files = array(
                  'jpeg',
                    'jpg',
                    'png'
                );
                $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION)); 
                if (in_array($ext, $supported_files)) {
                  echo '<img src="'.$newdir.''.$img.'"/>';
                } else {
                }
              }
              $imgs++;
            }
          }

        }
        $files++;
      }
    }
  ?>

【问题讨论】:

  • 这里有实际问题吗?还是您只是希望有人为您编写代码?另外,“按数据排序”是什么意思?
  • 如果你的意思是“按文件名排序”, natsort() 可能会为你服务 - php.net/manual/en/function.natsort.php
  • 使用上面的代码,我从代码正在运行的目录的子文件夹中获取图像(我正在获取图像),但按文件名排序。我希望他们按日期排序,意思是最后上传的图片在顶部。

标签: php sorting while-loop opendir readdir


【解决方案1】:

不要立即回显图像,而是将它们收集到数组中。 之后,您可以使用usort() 轻松对它们进行排序

另外 - 打开手柄后,您并没有关闭它们。

而且,RecursiveDirectoryIterator 可能比嵌套的 while 更适合这个。

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 1970-01-01
    • 2013-11-16
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多