Sorting in numeric and alphabetical order [duplicate]
I came across this block of code which pulls images from a folder specified and outputs them with the img
tag:
<?php
$url = "./images/";
$handle = opendir ($url);
while (false !== ($file = readdir($handle))) {
if($file != "." && $file != ".." && $file != basename(__FILE__)) {
echo '<a href="'.$url.$file.'" class="lightbox" title="'.$file.'"><img src="'.$url.$file.'" alt="" /></a><br />';
?>
This works great, but the only thing I am having issues with is the ordering of the images.
So, let's say in my images
folder, I have these images:
2.jpg
b.jpg
a.jpg
1.jpg
How can I make it so that it lists the images in numeric and alphabetical order? I would like the numbered images to come first then the alphabets, so it would list the images like this:
1.jpg
2.jpg
a.jpg
b.jpg
What you need is a natural language sort.
use the php function natsort().. here..
<?php
$url = "./images/";
$temp_files = scandir($url);
natsort($temp_files);
foreach($temp_files as $file)
{
if($file != "." && $file != ".." && $file != basename(__FILE__))
{
echo '<a href="'.$url.$file.'" class="lightbox" title="'.$file.'"><img src="'.$url.$file.'" alt="" /></a><br />';
}
}
?>
<?php
$url = "./test/";
$exclude = array('.', '..');
$files = array_diff(scandir($url), $exclude);
natsort($files);
print_r(array_values($files));
?>
Output:
Array
(
[0] => 1.jpg
[1] => 2.jpg
[2] => a.jpg
[3] => b.jpg
)
Instead of immediately echo-ing them, you can add the links to an array. Then use sort($array)
to place them in the right order, and echo them by going through each one in a foreach loop like: foreach($array as $image) { echo ... }
.
For more info, see: http://php.net/manual/en/function.sort.php
I would store the filenames in an array and then use sort()
to order the array. There is no easier way to do it due to the fact that reddir only returns the filenames like so:
The filenames are returned in the order in which they are stored by the filesystem.
The scandir()
and glob()
functions can both return arrays of sorted directory contents, or you can continue to use opendir/readdir()
to construct an array manually.
If the sort order (or lack thereof) is not what you prefer, then you can use any of the array sorting functions to manipulate the order however you like. I tend to like natcasesort()
.
精彩评论