[英]Displaying images 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" />';
}
}
一切正常,但是我該如何設置按名稱或其他方式顯示文件夾分類器,因為我真的需要對圖像進行分類,而此腳本僅顯示隨機圖像。謝謝。
您應該首先將圖像( $files
)存儲到數組中,例如$aImages[] = $file
。 您可以使用PHP中的多個排序函數對數組進行排序。 asort(), usort(), sort()...
參見http://php.net/manual/en/ref.array.php
您應該在這里找到答案: 在PHP中按創建/修改日期對文件進行排序
還有其他類似的帖子,您可以在其中獲得另一個有用的排序功能。
這樣您的代碼應如下所示:
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.