2

How can I sort this array by the value of the "time_slots" key? Even though the values are currently sequential, they will not always be. This scenario is not covered in the given solution of question. [time_slots] => 11:00 AM - 12:00 PM. Need solution based on AM and PM as a string in value.

 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
        )
)
Neeraj Sharma
  • 346
  • 1
  • 4
  • 16
  • 2
    Same question: https://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value – janfitz Jun 29 '17 at 09:41
  • 1
    this scenario is not covered in the given solution of question. [time_slots] => 11:00 AM - 12:00 PM. Need solution based on AM and PM as a string in value. – Neeraj Sharma Jun 29 '17 at 09:44
  • @NeerajSharma I have solution but this question is marked as duplicate so I can't answer it. You can request to reopen it – B. Desai Jun 29 '17 at 09:58

1 Answers1

0

Try this. But you have to change values of your time_slots to some better formatting which will help you to get the right oder.

<?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);
Tomas2D
  • 75
  • 1
  • 5