简体   繁体   English

在php中显示文件夹中的图像

[英]Displaying images from folder in php

Hello I have this code to show image from folder in php : 您好,我有这段代码来显示php中文件夹的图像:

$handle = opendir(dirname(realpath(__FILE__)).'/galerija/accomodation/');
while($file = readdir($handle)) {
    if($file !== '.' && $file !== '..') {
        echo '<img src="galerija/accomodation/'.$file.'" rel="colorbox" />';
    }
}

and it's working everthing is fine but how can I set to show folder sorter by name or something, because I really need to sort that images and this script show's only random images.Thank you. 一切正常,但是我该如何设置按名称或其他方式显示文件夹分类器,因为我真的需要对图像进行分类,而此脚本仅显示随机图像。谢谢。

Using glob and sort : 使用globsort

$files = glob("*.jpg");
sort($files);
foreach ($files as $file) {
    ....
}

You should first store the images ( $files ) to an array, for example $aImages[] = $file . 您应该首先将图像( $files )存储到数组中,例如$aImages[] = $file The you can use several sort functions from PHP to sort your array. 您可以使用PHP中的多个排序函数对数组进行排序。 asort(), usort(), sort()... . asort(), usort(), sort()... See http://php.net/manual/en/ref.array.php 参见http://php.net/manual/en/ref.array.php

You should find your answer here: Sorting files by creation/modification date in PHP 您应该在这里找到答案: 在PHP中按创建/修改日期对文件进行排序

There are other similar posts where you could get another usefull function for sorting. 还有其他类似的帖子,您可以在其中获得另一个有用的排序功能。

So that your code should look something like this: 这样您的代码应如下所示:

if($h = opendir(dirname(realpath(__FILE__)).'/galerija/accomodation/')) {
  $files = array();
  while(($file = readdir($h) !== FALSE){
    if($file !== '.' && $file !== '..'){
       $files[] = stat($file);
    }
  }

  // do the sort
  usort($files, 'sortByName');

  // do something with the files
  foreach($files as $file) {
            echo '<img src="galerija/accomodation/'.$file.'" rel="colorbox" />';
  }
}

//some functions you can use to sort the files
//sort by change time
//you can change filectime with filemtime and have a similar effect
function sortByChangeTime($file1, $file2){
    return (filectime($file1) < filectime($file2)); 
}

function sortByName{
    return (strcmp($file1,$file2)); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM