php - 按特定键的内部数组的值对 PHP 二维数组进行排序
问题描述
我有以下多个一维关联数组的二维索引数组:
Array (
[0] => Array (
[from] => Person 1
[to] => Person 2
[platform] => Instagram Direct Messaging
[date] => 2016/06/27
[time] => 12:00
[ampm] => PM
[specialcontent] => none
[content] => Hello
)
[1] => Array (
[from] => Person 1
[to] => Person 2
[platform] => Instagram Direct Messaging
[date] => 2016/06/27
[time] => 12:00
[ampm] => PM
[specialcontent] => none
[content] => How are you?
)
[2] => Array (
[from] => Person 2
[to] => Person 1
[platform] => Instagram Direct Messaging
[date] => 2016/06/27
[time] => 6:00
[ampm] => PM
[specialcontent] => none
[content] => Oh, hey there. I'm fine
)
[3] => Array (
[from] => Person 2
[to] => Person 1
[platform] => Instagram Direct Messaging
[date] => 2016/06/27
[time] => 6:01
[ampm] => PM
[specialcontent] => none
[content] => What about you?
)
)
我想按其中的date
字段(键)的值对内部数组进行排序,这意味着我必须按年、月、日对它们进行升序排序。我可以date
分别使用以下命令从 (key) 获取这些值:$year = substr($item['date'], 0, 4);
, $month = substr($item['date'], 5, 2);
, $day = substr($item['date'], -2);
. 我也知道我可能需要使用类似usort
or的函数array_multisort
,但我想不出如何创建一个函数,该函数按年、月、日返回数组的顺序date
。
解决方案
一个可能更简单的实现,也使用 usort,但利用了该功能strtotime
- 我们将所有日期/时间字段连接在一起,将它们转换为 unix 时间戳并升序排序。
usort($my_array, function($a, $b) {
$a = strtotime("{$a['date']} {$a['time']} {$a['ampm']}");
$b = strtotime("{$b['date']} {$b['time']} {$b['ampm']}");
if($a == $b) {
return 0;
}
return $a < $b ? -1 : 1;
});
推荐阅读
- c++ - 如何在线程池中正确分配 pthread 空闲状态?
- javascript - 如何在语法上制作 chrome 扩展?
- python - 如何在 django manytomany m2m_changed 中删除多个实例
- audiokit - AK麦克风追踪器。频率不准确(AudioKit 4.10.1)
- swiftui - 在 UITextField 与 UIViewRepresentable 和 SwifUI 之间绑定文本时出现问题
- flutter - fromJson 返回空值
- rest - Tomcat 阻止 PUT 请求
- python - 如何使用 mojang api 在 python 中获取 uuid?
- asp.net - 从 .aspx 页面抓取数据
- github - Elixir/mix: ** (停止) :eacces on Windows