How to sort an array of times chronologically?

前端 未结 8 927
梦毁少年i
梦毁少年i 2021-01-17 18:39

I have a non-associative array where the data that comes in is not sorted (I\'m receiving the data from an outside system and cannot force it to come into the array in sorte

8条回答
  •  滥情空心
    2021-01-17 19:40

    Sensibly sorting on time (chronologically) will call for strtotime().

    Here is a one-liner for you using array_multisort(). array_map() and strtotime() are called to generate an array to be used purely for the sorting order.

    array_multisort(array_map(function($v){return strtotime(strstr($v,'-',true));},$wedTrackTimes),$wedTrackTimes);
    

    For anyone that is lost in that syntax, here is the same functionality on more lines.

    Code: (Demo)

    $wedTrackTimes=[
        "9:30 AM-10:30 AM",
        "8:15 AM-9:15 AM",
        "12:30 PM-1:30 PM",
        "2:00 PM-3:00 PM",
        "3:30 PM-4:30 PM"
    ];
    
    foreach($wedTrackTimes as $time){  // iterate the time strings
        $timestamps[]=strtotime(strstr($time,'-',true));  // store the first time of the time range as a unix timestamp
    }
    array_multisort($timestamps,$wedTrackTimes);  // use $timestamps to sort $wedTrackTimes
    
    var_export($wedTrackTimes);
    

    Output:

    array (
      0 => '8:15 AM-9:15 AM',
      1 => '9:30 AM-10:30 AM',
      2 => '12:30 PM-1:30 PM',
      3 => '2:00 PM-3:00 PM',
      4 => '3:30 PM-4:30 PM',
    )
    

提交回复
热议问题