2013-02-22 78 views
0

我想按數字順序對目錄的內容進行排序。目錄的內容是圖像。現在圖像文件是隨機顯示的。每次將新圖像添加到目錄時,它都會在頁面上隨機顯示。請指教!謝謝!sort php array gallery directory

<?php 

// set image directory 
$image_dir = "main"; 

//Open images directory 
$dir = @ dir($image_dir); 
?> 


<?php 

//List files in images directory 
while (($file = $dir->read()) !== false) 
{ 
    // remove dir dots 
if ($file !== '.' && $file !== '..') { 

// print out images 
echo '<img src="'. $image_dir . '/' . $file .'" height="600" alt=""/>'; 

} 
} 
$dir->close(); 
?> 

回答

0

保持在臨時數組,然後排序它

while (($tfile = $dir->read()) !== false)$temp_arr[] = $tfile; 
sort($temp_arr); 
foreach(temp_arr as $file) 
{ 
// remove dir dots 
if ($file !== '.' && $file !== '..') { 

// print out images 
echo '<img src="'. $image_dir . '/' . $file .'" height="600" alt=""/>'; 

} 
} 
0

創建一個陣列的第一,排序,然後輸出的HTML。

<?php 

// set image directory 
$image_dir = "main"; 

//Open images directory 
$dir = @dir($image_dir); 

// create array to hold images 
$images = array(); 

//List files in images directory 
while (($file = $dir->read()) !== false) 
{ 
    // remove dir dots 
    if ($file !== '.' && $file !== '..') { 

     // add file to image array 
     $images[] = $file; 

    } 
} 

// close the directory 
$dir->close(); 

// sort the images by number 
sort($images, SORT_NUMERIC); 

// print out images 
foreach ($images as $file) 
{ 
    echo '<img src="'. $image_dir . '/' . $file .'" height="600" alt=""/>'; 
} 

?> 
1

文件加載到一個數組,然後進行排序,因爲你需要

$files = array(); 
while (($file = $dir->read()) !== false) 
{ 
    // remove dir dots 
    if ($file !== '.' && $file !== '..') { 
     // add file to array 
     $files[] = $file; 
    } 
} 

// sort array - I recommend "natural" sort, but check what other options are available 
// http://www.php.net/manual/en/array.sorting.php 

natsort($files); 

// print out images 
foreach($files as $file) { 
    echo '<img src="'. $image_dir . '/' . $file .'" height="600" alt=""/>';  
}  
0
<?php 

// set image directory 
$image_dir = "main"; 
$images=array(); 

//Open images directory 
$dir = @ dir($image_dir); 
?> 


<?php 

//List files in images directory 
while (($file = $dir->read()) !== false) 
{ 
    // remove dir dots 
if ($file !== '.' && $file !== '..') { 

$images[]=$file; 

} 
} 
$dir->close(); 
sort($images, SORT_NUMERIC); 
foreach ($images as $image) { 
// print out images 
    echo '<img src="'. $image_dir . '/' . $image .'" height="600" alt=""/>'; 
} 

?>