我有以下数组:
[0] => Array
(
[name] => The Name
[description] => description
[date] => Thur, May 5 @ 7:00 p.m.
[rating] => PG
[year] => 2011
)
[1] => Array
(
[name] => Name 2
[description] => description 2
[date] => Sun, May 8 @ 7:30 p.m.
[rating] => 14A
[year] => 2011
)
还有大约 5-10 个零件。
我最终想要做的是使用数组的日期部分按天对这些项目进行分组(即,“所有具有“日期”的项目都应按“5 月 8 日”分组)。
知道我该怎么做吗?请注意,“日期”字段原样存储在数据库中——这不是从 date() 转换而来的时间戳;或其他。
非常感谢!
最佳答案
创建您自己的排序函数并使用 usort 调用它.
例如(不考虑时间戳格式的复杂性):
function date_sort($a, $b) {
return strcmp($a['date'], $b['date']); //only doing string comparison
}
usort($array, 'date_sort');
要完成 date_sort,您需要以某种方式将日期转换为可比较的类型。这是将它们转换为 UNIX 时间戳的解决方案:
function convert_date($time) {
$time = substr($time, strpos($time, ',')+1);
$time = str_replace('@', ',', $time);
$time = str_replace('.', '', $time);
return strtotime($time);
}
function date_sort($a, $b) {
$a = convert_date($a['date']);
$b = convert_date($b['date']);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
关于php - 按子键日期对多维数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5777273/