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
        )
)
3
  • 2
    Same question: stackoverflow.com/questions/2699086/… Commented Jun 29, 2017 at 9: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. Commented Jun 29, 2017 at 9:44
  • @NeerajSharma I have solution but this question is marked as duplicate so I can't answer it. You can request to reopen it Commented Jun 29, 2017 at 9:58

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.