首页 > 解决方案 > 按特定键的内部数组的值对 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);. 我也知道我可能需要使用类似usortor的函数array_multisort,但我想不出如何创建一个函数,该函数按年、月、日返回数组的顺序date

标签: phparrays

解决方案


一个可能更简单的实现,也使用 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;
});

推荐阅读