PHP:如何对包含日期的字符串进行排序?

xqk2d5yq  于 2023-06-28  发布在  PHP
关注(0)|答案(3)|浏览(92)

使用PHP 7.4,我有一个名为$videoFiles的数组,其中包含以下视频文件的路径
/www/nginx/html/camera1/today/event69-27062023_115101.mp4
文件名格式为“event(event no)-(DDMMYY_HHMMSS).mp4”
我试着对这个数组排序,所以我有最早的第一个和最晚的最后一个。我试着用这个函数来做我需要做的事情:

<?php

usort(
      $videoFiles,
      create_function(
         '$a,$b',
         'return filemtime($a) - filemtime($b);'
      )
   );

但这并没有给予正确的结果。数组中的文件仍未排序。如何正确排序?

qlvxas9a

qlvxas9a1#

PHP usort(array &$array, callable $callback): true需要一个回调函数来执行实际的比较。
要比较文件名中的日期,首先需要隔离表示日期和时间的字符串,然后将其转换为DateTime对象。然后可以进行日期时间比较。
下面是代码示例:

function extractDate($string){
        $dateString = substr($string, strrpos($string, '-') + 1, 15);
        return DateTime::createFromFormat('dmY_his', $dateString);
    }

     usort($files, function ($file1,$file2){

        $date1 = extractDate($file1);
        $date2 = extractDate($file2);

        if ($date1 == $date2) {
            return 0;
        }
        return ($date1 < $date2) ? -1 : 1;

    });
yyyllmsg

yyyllmsg2#

$files = [
    '/www/nginx/html/camera1/today/event120-27062023_115101.mp4',
    '/www/nginx/html/camera1/today/event120-27062023_113101.mp4',
    '/www/nginx/html/camera1/today/event69-27062023_115101.mp4',
    '/www/nginx/html/camera1/today/event69-27062023_113101.mp4'
];

usort($files, function ($a, $b) {
    $dateA = substr($a, strrpos($a, '-') + 1, 15);
    $dateB = substr($b, strrpos($b, '-') + 1, 15);

    $dateTimeA = DateTime::createFromFormat('dmY_His', $dateA);
    $dateTimeB = DateTime::createFromFormat('dmY_His', $dateB);

    return $dateTimeB <=> $dateTimeA;
});

// Output
Array
(
    [0] => /www/nginx/html/camera1/today/event120-27062023_115101.mp4
    [1] => /www/nginx/html/camera1/today/event69-27062023_115101.mp4
    [2] => /www/nginx/html/camera1/today/event120-27062023_113101.mp4
    [3] => /www/nginx/html/camera1/today/event69-27062023_113101.mp4
)
nhhxz33t

nhhxz33t3#

试试这个。它解析时间戳,将其转换为sort-ready格式并进行比较:

$videoFiles = ['/www/nginx/html/camera1/today/event69-27062023_115101.mp4',
    '/www/nginx/html/camera1/today/event69-30062023_115101.mp4',
    '/www/nginx/html/camera1/today/event69-25062023_115101.mp4'
    ];

function getDateFromFilename($filename) {
    preg_match('/\d{8}\_\d{6}/',$filename,$matches);
    list($day,$time) = explode('_',$matches[0]);

    $dd = substr($day,0,2);
    $mm = substr($day,2,2);
    $yy = substr($day,4,4);

    return $yy.$mm.$dd.$time;
}

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

    $aTime = getDateFromFilename($a);
    $bTime = getDateFromFilename($b);
    if ($aTime > $bTime)  return 1;
    return -1;
});

相关问题