简体   繁体   English

排序php数组库目录

[英]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. 首先创建一个数组,对其进行排序,然后输出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