簡體   English   中英

排序php數組庫目錄

[英]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();
?> 

將文件加載到數組中,然后根據需要進行排序

$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=""/>';    
}    

將其保留在臨時數組中,然后對其進行排序

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=""/>';

}
}

首先創建一個數組,對其進行排序,然后輸出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=""/>';
}

?> 
<?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=""/>';
}

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM