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

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?

  • 写回答

3条回答 默认 最新

  • duanjiushu5063 2017-06-20 20:55
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题