dpwgzi7987 2011-02-23 16:50
浏览 45
已采纳

PHP自定义数组按年份和月份排序文件名,最新的第一个

I've got an array of files which looks like this:

array (
  0 => 'scpt-01-2010.phtml',
  1 => 'scpt-01-2011.phtml',
  2 => 'scpt-02-2010.phtml',
  3 => 'scpt-02-2011.phtml',
  4 => 'scpt-03-2010.phtml',
  5 => 'scpt-04-2010.phtml',
  6 => 'scpt-05-2010.phtml',
  7 => 'scpt-06-2010.phtml',
  8 => 'scpt-07-2010.phtml',
  9 => 'scpt-08-2010.phtml',
  10 => 'scpt-09-2010.phtml',
  11 => 'scpt-10-2010.phtml',
  12 => 'scpt-11-2010.phtml',
  13 => 'scpt-12-2010.phtml',
);

How can I sort it so that 2011 files appear first, in order of month (so it should lead with scpt-02-2011.phtml)?

I've tried the main sorting functions like natsort, rsort, arsort etc but I'm not getting anywhere fast!

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • duanjun7801 2011-02-23 16:54
    关注
    function customSort($a, $b) {
        // extract the values with a simple regular expression
        preg_match('/scpt-(\d{2})-(\d{4})\.phtml/i', $a, $matches1);
        preg_match('/scpt-(\d{2})-(\d{4})\.phtml/i', $b, $matches2);
    
        // if the years are equal, compare by month
        if ($matches2[2] == $matches1[2]) {
            return $matches2[1] - $matches1[1];
        // otherwise, compare by year
        } else {
            return $matches2[2] - $matches1[2];
        }
    }
    
    // sort the array
    usort($array, 'customSort');
    

    This method uses usort() to sort the array, passing the name of our comparison function.

    http://php.net/usort

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目