Using PHP 7.4 I have an array called $videoFiles
which contains paths to video files like this
/www/nginx/html/camera1/today/event69-27062023_115101.mp4
The file name format is "event(event no)-(DDMMYY_HHMMSS).mp4"
I’m trying to sort this array so I have earliest first and latest last. I tried using this function to do what I need:
<?php
usort(
$videoFiles,
create_function(
'$a,$b',
'return filemtime($a) - filemtime($b);'
)
);
But this didn’t give the right result. The files are still unsorted in the array. How do I get the sort done correctly?
3
Answers
Try this one. It parses the timestamps, converts them into sort-ready format and compares them:
PHP
usort(array &$array, callable $callback): true
needs a callback to a function that carries out the actual comparison.To compare dates in your file names you first need to isolate the string that represents a date plus time, and then convert it to a DateTime object. Then a DateTime comparison can happen.
Here is the code sample: