Php 使用usort对多维数组进行排序的表示法
我希望先按Php 使用usort对多维数组进行排序的表示法,php,arrays,sorting,usort,Php,Arrays,Sorting,Usort,我希望先按match\u formatted\u date然后按match\u localteam\u name对以下数组进行排序$json\u a(从json文件中解码) array(4) { ["APIRequestsRemaining"]=> int(920) ["matches"]=> array(3) { [0]=> array(3) { ["match_id"]=> s
match\u formatted\u date
然后按match\u localteam\u name
对以下数组进行排序$json\u a
(从json文件中解码)
array(4) {
["APIRequestsRemaining"]=> int(920)
["matches"]=> array(3) {
[0]=> array(3) {
["match_id"]=> string(7) "1999477"
["match_formatted_date"]=> string(6) "16.05.2015"
["match_localteam_name"]=> string(7) "Burnley" }
[1]=> array(3) {
["match_id"]=> string(7) "1999478"
["match_formatted_date"]=> string(10) "16.05.2015"
["match_localteam_name"]=> string(3) "QPR"
}
[2]=> array(3) {
["match_id"]=> string(7) "1999479"
["match_formatted_date"]=> string(10) "16.05.2015"
["match_localteam_name"]=> string(7) "Arsenal"
}
}
["Action"]=> string(5) "today"
}
我尝试按如下方式调用usort函数:
function cmp($a, $b) {
// sort by ['match_formatted_date']
$retval = strnatcmp(substr($b['match_formatted_date'],0,10), substr($a['match_formatted_date'],0,10));
// if identical, sort by ['match_localteam_name']
if(!$retval) $retval = strnatcmp($a['match_localteam_name'], $b['match_localteam_name']);
return $retval;
}
$matches = $json_a['matches'];
usort($matches, 'cmp');
然而,它似乎没有对记录进行排序。我已经读了很多关于usort的书,但我怀疑问题在于我函数中的符号格式。我也试过
$a['matches']['match_date']
,但没有乐趣 您试图通过首先比较日期对条目进行排序。但是,如果您的日期格式为16.05.2015
,则使用strnatcmp()
,您将始终首先按月日排序,然后按月排序,最后按年排序,这实际上毫无意义。更糟糕的是,您还将日期与格式May 16
混合在一起,这比第一种格式更糟糕
在比较之前,您必须将日期转换为常见格式,如
Ymd
,例如20150516
,以便进行正确的比较。您还必须决定如何处理您甚至没有日期的5月16日——它是在2016年5月15日之前还是之后?您应该将日期转换为时间戳,并比较这些时间戳,而不是原始字符串
替换此项:
// sort by ['match_formatted_date']
$retval = strnatcmp(substr($b['match_formatted_date'],0,10), substr($a['match_formatted_date'],0,10));
为此:
// sort by ['match_formatted_date']
$retval =
strtotime($a['match_formatted_date'])
- strtotime($b['match_formatted_date']);
5月16日是一个转录错误,应该是2015年5月16日。已更正问题。请在
usort()
勾选答案后发布结果数组的var\u dump
,因为它既注意到了问题,又提出了改进建议。