我有一个带有文件名的示例数组:
$test_array = array (
'video-start-1537482914-stop-1537483670.zip',
'video-start-1537533156-stop-1537534299.zip',
'video-start-1537534300-stop-1537534630.zip',
'video-start-1537090052-stop-1537091001.zip'
);
我想从每个文件中获取开始时间戳,然后将它们按数组排序。我尝试了preg_match,但它仅适用于字符串,不适用于数组。我该如何实现?
答案 0 :(得分:0)
public function testSort()
{
$test_array = array (
'video-start-1537482914-stop-1537483670.zip',
'video-start-1537533156-stop-1537534299.zip',
'video-start-1537534300-stop-1537534630.zip',
'video-start-1537090052-stop-1537091001.zip'
);
usort($test_array, function($a, $b) {
return ((int)explode('-',$a)[2] < (int)explode('-',$b)[2]) ? -1 : 1;
});
foreach($test_array as &$line) {
echo $line . PHP_EOL;
}
}
答案 1 :(得分:0)
尝试一下:
<?php
$test_array = array(
'video-start-1537482914-stop-1537483670.zip',
'video-start-1537533156-stop-1537534299.zip',
'video-start-1537534300-stop-1537534630.zip',
'video-start-1537090052-stop-1537091001.zip'
);
foreach ($test_array as $item){
preg_match('/video-start-(.*?)-stop-/', $item, $match);
$timespan[] = $match[1];
}
//sorts an associative array in ascending order.
asort($timespan);
var_dump($timespan);
?>
输出start timestamp
:
array (size=4)
3 => string '1537090052' (length=10)
0 => string '1537482914' (length=10)
1 => string '1537533156' (length=10)
2 => string '1537534300' (length=10)