Php 按日期对数组键排序
如何使用键按日期对该数组进行排序Php 按日期对数组键排序,php,Php,如何使用键按日期对该数组进行排序 Array ( [Jun '12] => 2037 [May '12] => 4615 [Apr '12] => 4175 [Mar '12] => 4548 [Feb '12] => 2758 [Jan '12] => 3077 [Jul '12] => 0 ) 我用这个回调函数尝试了uksort,但没有这样的运气 function datediff($a, $
Array
(
[Jun '12] => 2037
[May '12] => 4615
[Apr '12] => 4175
[Mar '12] => 4548
[Feb '12] => 2758
[Jan '12] => 3077
[Jul '12] => 0
)
我用这个回调函数尝试了uksort,但没有这样的运气
function datediff($a, $b) {
strtotime($a);
$a = date('U',strtotime($a));
$b = date('U',strtotime($b));
if ($a == $b) $r = 0;
else $r = ($a > $b) ? 1: -1;
return $r;
}
感谢您的帮助。
谢谢 您需要将钥匙中的“20”替换为“20” 这应该是一个带有一些测试代码的工作示例
$values = array
(
"Jun '12" => 2037,
"May '12" => 4615,
"Apr '12" => 4175,
"Mar '12" => 4548,
"Feb '12" => 2758,
"Jan '12" => 3077,
"Jul '12" => 0
);
//I tried uksort with this callback function with no such luck.
function datediff($a, $b) {
strtotime($a);
$a = date('U',strtotime(str_replace("'", "20", $a)));
$b = date('U',strtotime(str_replace("'", "20", $b)));
if ($a == $b) $r = 0;
else $r = ($a > $b) ? 1: -1;
return $r;
}
foreach($values as $key=>$val) {
echo $key . " = " . strtotime(str_replace("'", "20", $key)) . "\n";
}
// before
print_r($values);
uksort($values, "datediff");
// after
print_r($values);
datediff()始终返回0,因为strottime()不理解12前面的单个引号。因此,$a和$b是空的(因此相等)
因此,如果可能的话,你应该使用类似“Mar'12”的东西作为你的钥匙,而不是“Mar'12”。否则,在调用strottime()之前,您必须在datediff中添加某种字符串操作。您可以创建自定义映射
$date_map = array("Jan" => 1, "Feb" => 2, "Mar" => 3, "Apr" => 4, "May" => 5, "Jun" => 6, "Jul" => 7, "Aug" => 8, "Sep" => 9, "Oct" => 10, "Nov" => 11, "Dec" => 12);
function date_compare($a, $b) {
global $date_map;
$a_month = $date_map[substr($a, 0, 3)];
$b_month = $date_map[substr($b, 0, 3)];
if ($a_month == $b_month) return 0;
return ($a_month > $b_month) ? 1 : -1;
}
使用日期\u与uksort比较您是否尝试过在没有uksort的情况下使用datediff()函数?它是否为不同的$a、$b返回正确的值?您是否尝试过调用date()是否返回您期望的结果?您的strotime无法使用提供的键。如我所见,PHP不支持此日期格式: