php - 基于dateTime排序多维数组

时间:2017-11-30 17:44:46

标签: php arrays sorting datetime multidimensional-array

Array
(
    [0] => Array
        (
            [start] => 15:00
            [end] => 15:25
        )

    [1] => Array
        (
            [start] => 17:00
            [end] => 17:20
        )

    [2] => Array
        (
            [start] => 11:15
            [end] => 11:35
        )

    [3] => Array
        (
            [start] => 10:50
            [end] => 11:20
        )

    [4] => Array
        (
            [start] => 14:20
            [end] => 14:25
        )
)

我想使用[dateTime]按结束时间键对上面的数组进行排序,最终输出应为:

Array
(
    [0] => Array
        (
            [start] => 10:50
            [end] => 11:20
        )

    [1] => Array
        (
            [start] => 11:15
            [end] => 11:35
        )

    [2] => Array
        (
            [start] => 14:20
            [end] => 14:25
        )

    [3] => Array
        (
            [start] => 15:00
            [end] => 15:25
        )

    [4] => Array
        (
            [start] => 17:00
            [end] => 17:20
        )
)

任何人都可以使用[dateTime]

建议一种基于结束时间键对此进行排序/排序的方法

1 个答案:

答案 0 :(得分:1)

您可以使用usort,为DateTime值创建['end'],并在比较函数中对它们进行比较。

例如:

$arrays = [
    [
        "start" => "15:00",
        "end" => "15:25"
    ],
    [
        "start" => "17:00",
        "end" => "17:20"
    ],
    [
        "start" => "11:15",
        "end" => "11:35"
    ],
    [
        "start" => "10:50",
        "end" => "11:20"
    ],
    [
        "start" => "14:20",
        "end" => "14:25"
    ],
];

usort($arrays, function($a, $b) {
    return new DateTime($a['end']) > new DateTime($b['end']);
});

Demo