按子键日期对多维数组进行排序?
我有以下数组:
[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() 或其他内容转换而来的时间戳
。
I have the following array:
[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
)
There are about 5-10 more parts.
What I'm ultimately wanting to do is to use the date part of the array to group these items by day (I.e., "all items with "date" falling into "May 8" should be grouped as such).
Any idea how I'd go about this? Note that the "date" field is stored as such in DB -- that's not a timestamp converted from date(); or whatever.
Many thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
创建您自己的排序函数并使用 usort 调用它。
例如(不考虑时间戳格式的复杂性):
要完成 date_sort,您需要以某种方式将日期转换为可比较的类型。这是将它们转换为 UNIX 时间戳的解决方案:
Create your own sort function and call it using usort.
For example (not considering the intricacies of your timestamp format):
To complete date_sort, you'll somehow need to convert the dates to comparable types. Here's a solution which converts them to UNIX timestamps:
使用@Emil Vikström解决方案,用strtotime作为比较函数
function date_sort($a, $b) {
$a = strtotime($a['date']);
$b = strtotime($b['日期']);
返回($a==$b)? 0 : ($a>$b ? - 1 : 1);
}
usort($array, 'date_sort');
https://www.php.net/manual/en/function.strtotime。 php 应该处理大多数用英语编写的文本日期。
Use @Emil Vikström solution, with strtotime as comparing function
function date_sort($a, $b) {
$a = strtotime($a['date']);
$b = strtotime($b['date']);
return ($a == $b) ? 0 : ($a>$b ? - 1 : 1);
}
usort($array, 'date_sort');
https://www.php.net/manual/en/function.strtotime.php should deal with most textual dates written in english.
试试这个
$arrArray 有你指定的数组;
Try this
$arrArray has array you have specified;
要按日期对数据进行分组,请运行这个小循环
,您可以使用 usort 按时间对每个组进行排序
For grouping your data by date, run this little loop
And you can use usort for sorting by time into each group