douhao1956
2017-06-20 18:45
浏览 109
已采纳

PHP按文件名中的数字排序数组

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?

图片转代码服务由CSDN问答提供 功能建议

我正在开发一个照片库,可以根据文件名的数量自动对照片进行排序。

我有以下代码:

  // 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); 
 \  n 
 //重置数组列表
 $ first = reset($ files_thumbs); 
 $ last = end($ files_thumbs); 
 //从数组值匹配和拆分文件名 - 图像编号
preg_match(“/(  \ d +(?: -  \ d +)*)/“,”$ first“,$ matches); 
 $ firstimage = $ matches [1]; 
preg_match(”/(\ d +(?: -  \ d +)*  )/“,”$ last“,$ matches); 
 $ lastimage = $ matches [1]; 
   
 
 

但是当我有像 photo-Aname_0333.jpg photo-Bname_0222.jpg ,它做的 从 photo-Aname_0333 开始,而不是 0222

如何通过文件名编号对其进行排序?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题