$array = array("2011-September_38","2011-June_4","2010-November_9","2011-November_29","2010-December_19");
我想按如下方式对这个数组字符串进行排序,它应该先对年份进行排序,然后对它进行排序,
渴望输出
Array ( [0] => 2010-Marh_19
[1] => 2010-November_9
[2] => 2011-June_4
[3] => 2011-September_38
[4] => 2011-November_29 )
我尝试了一些东西,任何人都可以将我的功能绑定到年份http://codepad.org/skEiUkTC
答案 0 :(得分:2)
试试这段代码:
<?php
$array = array("2011-September_38","2011-June_4","2010-November_9","2011-November_29","2010-December_19");
function monthCompare($a, $b) {
$da = strtotime(strstr($a, '_', true));
$db = strtotime(strstr($b, '_', true));
return $da > $db;
}
usort($array, "monthCompare");
print_r($array);
?>
<强>输出强>
Array
(
[0] => 2010-November_9
[1] => 2010-December_19
[2] => 2011-June_4
[3] => 2011-September_38
[4] => 2011-November_29
)
答案 1 :(得分:1)
对此的一个简单解决方案是将每个值转换为具有DateTime::createFromFormat的对象,对它们进行排序,然后再次输出值。
在我看到这个问题之前,我从来没有玩过DateTime对象,但它们很棒且易于使用,createFromFormat
非常有意义。
$array = array("2011-September_30","2011-June_4","2010-November_9","2011-November_29","2010-December_19");
foreach($array as $item)
{
$timestamps[] = DateTime::createFromFormat('Y-F_d',$item);
}
sort($timestamps);
foreach($timestamps as $timestamp)
{
$newarray[] = $timestamp->format('Y-F_d');
}
会给你
Array
(
[0] => 2010-November_09
[1] => 2010-December_19
[2] => 2011-June_04
[3] => 2011-September_30
[4] => 2011-November_29
)