Harpreet Singh
Harpreet Singh

Reputation: 979

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"]

Upvotes: 4

Views: 288

Answers (5)

mickmackusa
mickmackusa

Reputation: 47904

You do not need to parse these time expressions with strtotime() or a datetime method. Just sort naturally.

Code: (Demo)

sort($totlahourdat1, SORT_NATURAL);

Upvotes: 0

Jim Wright
Jim Wright

Reputation: 6058

You can use usort() to write a custom sorting function.

$times = array("9:30", "15:00", "13:00");

usort($times, function ($a, $b) {
    $a = strtotime($a);
    $b = strtotime($b);
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? 1 : -1;
});

If you are using PHP7, you could use the spaceship operator to greatly reduce the size of the sorting function.

$times = array("9:30", "15:00", "13:00");

usort($times, function ($a, $b) {
    return strtotime($b) <=> strtotime($a);
});

Upvotes: 1

Accountant م
Accountant م

Reputation: 7483

Your problem is much simpler than you think. you just forgot to use the proper order

Just Order by ASC

array_multisort($totlahourdat1, SORT_ASC);

See demo here (https://eval.in/835356)

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

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

Upvotes: 3

squareCircle
squareCircle

Reputation: 302

Use natsort($array) see function definition

Upvotes: 3

Related Questions