如何从PHP中的值数组中排序特定的字符串?
问题描述:
$array = array("2011-September_38","2011-June_4","2010-November_9","2011-November_29","2010-December_19");
i want to sort this array strings as following, it should sort the year first, then it should sort the month,
DESIRED OUTPUT
Array ( [0] => 2010-Marh_19
[1] => 2010-November_9
[2] => 2011-June_4
[3] => 2011-September_38
[4] => 2011-November_29 )
I've tried something, could anyone bind my function to sort year then month http://codepad.org/skEiUkTC
答
Try this code:
<?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);
?>
OUTPUT
Array
(
[0] => 2010-November_9
[1] => 2010-December_19
[2] => 2011-June_4
[3] => 2011-September_38
[4] => 2011-November_29
)
答
So a simple solution to this, is to turn each of the values into a objects with DateTime::createFromFormat, sort them, and then outputting the values again.
Before i saw this question i had never played with DateTime objects, but they are awesome and easy to work with, and createFromFormat
makes perfectly sense.
$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');
}
will give you
Array
(
[0] => 2010-November_09
[1] => 2010-December_19
[2] => 2011-June_04
[3] => 2011-September_30
[4] => 2011-November_29
)