4

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"]
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Harpreet Singh
  • 999
  • 9
  • 19

5 Answers5

3

Use natsort($array) see function definition

squareCircle
  • 192
  • 1
  • 13
  • it works but its not changing key values which i need in another loop – Harpreet Singh Jul 20 '17 at 17:52
  • @Harpreet then you can call `array_values()` or just use [my answer](https://stackoverflow.com/a/73810873/2943403) ...which is obviously simpler than the accepted answer. – mickmackusa Oct 12 '22 at 11:32
3

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

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
1

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);
});
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Jim Wright
  • 5,905
  • 1
  • 15
  • 34
0

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)

Accountant م
  • 6,975
  • 3
  • 41
  • 61
0

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

Code: (Demo)

sort($totlahourdat1, SORT_NATURAL);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136