简体   繁体   中英

sort php array gallery directory

I would like to sort the contents of the directory in numerical order. The contents of the directory are images. Right now the image files are displayed randomly. Each time a new image is added to the directory, it displays randomly on the page. Please advise! Thank you!

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

Load files into an array, then sort as you need

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

keep it in temporary array and then sort it

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

}
}

Create an array first, sort it, then output the 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=""/>';
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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