views:

344

answers:

5

know nothing about php, but I have this script that reads a folder and displays a thumbnail gallery, problem is it dosent display alphabetically. Have searched the net and seen that sort does this but have no idea where to start any help would be much appreciated.

heres the script

$sitename = $row_wigsites['id'];     
$directory = 'sites/'.$sitename.'/pans';
$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$i=0;

$dir_handle = @opendir($directory) or die("There is an error with your image directory!");

while ($file = readdir($dir_handle)) 

{

if($file=='.' || $file == '..') continue;

$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));

$title = implode('.',$file_parts);
$title = htmlspecialchars($title);


$nomargin='';

if(in_array($ext,$allowed_types))
{

    if(($i+1)%4==0) $nomargin='nomargin';

    echo '
    <div class="pic '.$nomargin.'" style="background:url('.$directory.'/'.$file.') no-repeat 50% 50%;">
    <a href="'.$directory.'/'.$file.'" title="Panoramic Stills taken at '.$title.'°" rel="pan1" target="_blank">'.$title.'</a>
    </div>';

    $i++;
}
}

closedir($dir_handle);
A: 

add the sort line as given below

$file_parts = explode('.',$file);
sort($file_parts) or die("sorting failed");
$ext = strtolower(array_pop($file_parts));
Samuel
That would just sort the file parts (file name, extension, etc).
Shawn Steward
A: 

It's probably easiest to put the values from the files into an array, then sort the array before outputting it to the page.

Shawn Steward
+1  A: 

Try using glob instead of opendir, something like:

$i=0;
foreach (glob($directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $file){
    if($file=='.' || $file == '..') continue;
    $file_parts = explode('.',$file);
    $ext = strtolower(array_pop($file_parts));
    $title = basename($file);
    $title = htmlspecialchars($title);
    $nomargin='';
    if(($i+1)%4==0) $nomargin='nomargin';
    echo '
    <div class="pic '.$nomargin.'" style="background:url('.$file.') no-repeat 50% 50%;">
    <a href="'.$file.'" title="Panoramic Stills taken at '.$title.'°" rel="pan1" target="_blank">'.$title.'</a>
    </div>';
    $i++;
}

Glob should return sorted list of files.

EDIT: Thanks to Doug Neiner for a tip ;)

habicht
@Habicht you are on the right track, but instead of `*.*` try this: `glob($directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE)` and you can remove the `if(in_array` test.
Doug Neiner
Habicht this works a dream only problem now my thumbnail titles include the directory instead of just the file name
David Cahill
Ah yes, you see - glob returns full path to the file, including directory. So you need to use basename() to get filename itself.Updated the code in the answer.
habicht
Spot on works a Treat.... much appreciated!!!!
David Cahill
A: 

Glad I just found this - sorted my "sorting" issue! Thanks.

squareart
A: 

Bardzo dobrze wyjaśniona sprawa sortowania, dzięki

elgo