Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting time array giving wrong values in PHP

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"]
like image 267
Harpreet Singh Avatar asked Jan 30 '23 23:01

Harpreet Singh


2 Answers

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

like image 164
Anant Kumar Singh Avatar answered Feb 03 '23 07:02

Anant Kumar Singh


Use natsort($array) see function definition

like image 41
squareCircle Avatar answered Feb 03 '23 06:02

squareCircle