Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

html - PHP sort array by number in filename

I am working on a photo gallery that automatically sorts the photos based on the numbers of the file name.

I have the following code:

//calculate and sort 
$totaal = 0;
if($handle_thumbs = opendir('thumbs')){
    $files_thumbs = array();
    while(false !== ($file = readdir($handle_thumbs))){
        if($file != "." && $file != ".."){
            $files_thumbs[] = $file;
            $totaal++;
        }
    }
    closedir($handle_thumbs);
}
sort($files_thumbs);


//reset array list
$first = reset($files_thumbs);
$last = end($files_thumbs);
//match and split filenames from array values - image numbers
preg_match("/(d+(?:-d+)*)/", "$first", $matches);
$firstimage = $matches[1];
preg_match("/(d+(?:-d+)*)/", "$last", $matches);
$lastimage = $matches[1];

But when i have file names like photo-Aname_0333.jpg, photo-Bname_0222.jpg, it does start with the photo-Aname_0333 instead of the 0222.

How can i sort this by the filename numbers?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

usort is a php function to sort array using values. usort needs a callback function that receives 2 values.

In the callback, depending of your needs, you will be return the result of the comparision 1, 0 or -1. For example to sort the array asc, I return -1 when the firts value of the callback is less than second value.

In this particular case I obtain the numbers of the filename, and compare it as string, is not necesary to cast as integer.

<?php

$photos=[
    'photo-Bname_0222.jpg',
    'photo-Aname_0333.jpg', 
    'photo-Cname_0111.jpg', 

];

usort($photos, function ($a, $b) {

    preg_match("/(d+(?:-d+)*)/", $a, $matches);
    $firstimage = $matches[1];
    preg_match("/(d+(?:-d+)*)/", $b, $matches);
    $lastimage = $matches[1];

    if ($firstimage == $lastimage) {
        return 0;
    }
    return ($firstimage < $lastimage) ? -1 : 1;
});

print_r($photos);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...