PHP自定义数组按年份和月份对文件名排序,最新的优先
我有一个文件数组,如下所示:PHP自定义数组按年份和月份对文件名排序,最新的优先,php,arrays,sorting,Php,Arrays,Sorting,我有一个文件数组,如下所示: 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
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',
);
如何对其进行排序,以使2011个文件按月份顺序首先显示(因此应以scpt-02-2011.phtml开头)
我尝试过natsort、rsort、arsort等主要的排序功能,但进展不快
提前谢谢
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');
此方法使用usort()
对数组进行排序,并传递比较函数的名称
使用它,您可以编写自己的回调并按自己的方式排序。无需为此任务推出正则表达式引擎。您需要在连字符上分解,按相反顺序比较元素,并按降序排序。只要您理解
返回$b$a,下面的翻译就是字面意思代码>表示“降序排序”。由于您的所有文件扩展名都相同,因此扩展名可能会附加到年份值,而不会损害准确性
代码:()
换言之,对于像scpt-02-2011.phtml这样的文件,爆炸会创建:
['scpt', '02', '2011.phtml']
然后反过来变成:
['2011.phtml', '02', 'scpt']
然后,以DESC方式逐步将每个元素与另一个文件名的相应元素进行比较
['scpt', '02', '2011.phtml']
['2011.phtml', '02', 'scpt']