You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按含AM/PM格式时间范围的列排序PHP二维数组

解决PHP中AM/PM格式时间范围数组的排序问题

你之前的代码报错是因为直接对AM/PM格式的字符串做减法运算,PHP无法将这类字符串解析为有效的数值,自然没法正确排序。要解决这个问题,核心是把每个时间范围的起始时间转换成可比较的时间戳或DateTime对象,再进行排序。

方法一:使用strtotime转换时间戳排序

先从time字段中提取起始时间,用strtotime将其转为时间戳,再比较两个时间戳的大小:

usort($props, function ($a, $b) {
    // 提取起始时间并去除前后空格
    $startTimeA = trim(explode(' - ', $a['time'])[0]);
    $startTimeB = trim(explode(' - ', $b['time'])[0]);
    
    // 转换为时间戳后比较
    return strtotime($startTimeA) - strtotime($startTimeB);
});

方法二:使用DateTime对象排序

如果需要更严谨的时间处理(比如避免strtotime的某些兼容性问题),可以用DateTime类:

usort($props, function ($a, $b) {
    $startTimeA = trim(explode(' - ', $a['time'])[0]);
    $startTimeB = trim(explode(' - ', $b['time'])[0]);
    
    $dateA = DateTime::createFromFormat('h:i:A', $startTimeA);
    $dateB = DateTime::createFromFormat('h:i:A', $startTimeB);
    
    // PHP 7+可直接用太空船运算符比较对象
    return $dateA <=> $dateB;
    // 兼容低版本PHP可改用时间戳差值:return $dateA->getTimestamp() - $dateB->getTimestamp();
});

验证结果

运行上述代码后,$props会按照时间范围的起始时间从小到大排序,得到你需要的结果:

[
    ['name' => 'History', 'time' => '11:30:AM - 01:30:PM'],
    ['name' => 'French', 'time' => '01:31:PM - 03:00:PM'],
    ['name' => 'Mathmatics', 'time' => '03:01:PM - 04:50:PM'],
];

内容的提问来源于stack exchange,提问作者Ishrat Hossain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 07:40:31