Search code examples
phparrayssortingtimenatural-sort

Sort array of time strings naturally


I need to sort an array of time strings (which are not zero padded) naturally.

Sample data:

$totlahourdat1 = ["9:30", "15:00", "13:00"];

When I try array_multisort($totlahourdat1, SORT_DESC), the data appears unchanged.

My actual code:

while($row11 = mysqli_fetch_array($hourget))
{
    $totlahourdat1[] = strtotime($row11['hours']); 
}   

array_multisort($totlahourdat1, SORT_DESC);

foreach ($totlahourdat1 as $time) {
    $totlahourdat[] = date("h:i",$time);
}

echo "<pre>";
    var_dump($totlahourdat);
echo "</pre>";

Ultimately, the array data should be ordered from earliest time to latest time:

["9:30", "13:00", "15:00"]

Solution

  • Simply do like below:-

    $time = array(0=>"9:30",1=>"15:00",2=>"13:00");
    function timecompare($a,$b)
    {
        return strtotime($a) < strtotime($b) ? -1: 1;
    }
    uasort($time ,'timecompare');
    
    print_r(array_values($time));
    

    Output:-https://eval.in/835353