2012-10-09 73 views
0

你好,我有這樣的代碼在PHP中的文件夾中顯示的圖像:顯示圖像

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

,它的工作寄託都很好,但是我怎麼可以設置顯示的名字什麼的文件夾分類器,因爲我真的需要對這些圖像進行排序,並且這個腳本只顯示隨機圖像。謝謝。

+1

陣列中的存儲文件的名稱,排序的數組,然後顯示出來。 – Dev

回答

1

你應該在這裏找到答案: Sorting files by creation/modification date in 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)); 
} 
+0

「語法錯誤,第5行」php路徑中出現意外的T_IF「我該如何解決這個問題 –

+0

我最後一次編輯應該做的伎倆,有一個分號不屬於那裏,我的錯 – decebal

2

glob使用和sort

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

你可以把我的代碼全部放在一起嗎 –

+2

不,我不會爲你寫代碼,你必須自己動手。 – Sjoerd

0

您應的圖像($files)第一存儲陣列,例如$aImages[] = $file。您可以使用PHP的幾種排序函數對數組進行排序。 asort(), usort(), sort()...。見http://php.net/manual/en/ref.array.php