如何在PHP中对多维数组进行排序

时间:2017-06-29 09:39:42

标签: php arrays sorting

如何按“time_slots”键的值对此数组进行排序?尽管这些值目前是顺序的,但它们并不总是如此。在给定的问题解决方案中未涵盖此方案。 [time_slots] =>上午11:00 - 中午12:00 。需要基于 AM和PM 的解决方案作为值中的字符串。

 Array
(
    [0] => Array
        (
            [id] => 38
            [time_slots] => 9:00 AM - 10:00 AM
            [cutt_off_time] => 08:45 AM
        )

    [1] => Array
        (
            [id] => 39
            [time_slots] => 10:00 AM - 11:00 AM
            [cutt_off_time] => 09:45 AM
        )

    [2] => Array
        (
            [id] => 40
            [time_slots] => 11:00 AM - 12:00 PM
            [cutt_off_time] => 10:45 AM
        )

    [3] => Array
        (
            [id] => 41
            [time_slots] => 12:00 PM - 1:00 PM
            [cutt_off_time] => 11:45 AM
        )

    [4] => Array
        (
            [id] => 42
            [time_slots] => 1:00 PM - 2:00 PM
            [cutt_off_time] => 12:45 PM
        )

    [5] => Array
        (
            [id] => 43
            [time_slots] => 2:00 PM - 3:00 PM
            [cutt_off_time] => 01:45 PM
        )

    [6] => Array
        (
            [id] => 44
            [time_slots] => 2:30 PM - 6:00 PM
            [cutt_off_time] => 06:00 PM
        )

    [7] => Array
        (
            [id] => 45
            [time_slots] => 5:00 AM - 7:00 AM
            [cutt_off_time] => 05:30 AM
        )

    [8] => Array
        (
            [id] => 46
            [time_slots] => 5:00 PM - 8:00 PM
            [cutt_off_time] => 07:15 PM
        )
)

1 个答案:

答案 0 :(得分:0)

试试这个。但您必须将 time_slots 的值更改为更好的格式,以帮助您获得正确的内容。

<?php

function sort_by_col(&$arr, $col) {
    $sorted = array();

    foreach ($arr as $key => $row) {
        $sorted[$key] = $row[$col];
    }

    array_multisort($sorted, SORT_REGULAR, $arr);
}

sort_by_col($arr, 'time_slots');

// Result
var_dump($arr);