Sort an array of time specifying invalid values in PHP
I have a php array, for example:
array(3) {
[0]=>
string(4) "9:30"
[1]=>
string(5) "15:00"
[2]=>
string(5) "13:00"
}
After sorting this time, I get the wrong data. I sort it using a function array_multisort.
This is what I get after sorting the time
array(3) {
[0]=>
string(5) "03:00"
[1]=>
string(5) "01:00"
[2]=>
string(5) "09:30"
}
This is my code.
First, I convert my time to unix time using the strtotime function, then sorting it like this:
while($row11 = mysqli_fetch_array($hourget))
{
$totlahourdat1[] = strtotime($row11['hours']);
$totlahourdat2[] = $row11['hours'];
}
echo "<pre>";
var_dump($totlahourdat2);
echo "</pre>";
//sort data
array_multisort($totlahourdat1, SORT_DESC);
//var_dump($totlahourdat);
foreach($totlahourdat1 as $time){
$totlahourdat[] = date("h:i",$time);
}
echo "<pre>";
var_dump($totlahourdat);
echo "</pre>";
if I print an array $totlahourdat1, then I get the following:
array(3) {
[0]=>
int(1500535800)
[1]=>
int(1500555600)
[2]=>
int(1500548400)
}
My result should look like this:
array(3) {
[0]=>
string(4) "9:30"
[1]=>
string(5) "13:00"
[2]=>
string(5) "15:00"
}
Any help would be greatly appreciated.
Just follow these steps: -
$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));
Exit: - https://eval.in/835353
You can use usort()to write a custom sort 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 can use the spacecraft operator to significantly reduce the size of the sort function.
$times = array("9:30", "15:00", "13:00");
usort($times, function ($a, $b) {
return strtotime($b) <=> strtotime($a);
});
Your problem is much simpler than you think. you just forgot to use the correct order
Order only ASC
array_multisort($totlahourdat1, SORT_ASC);
See the demo here ( https://eval.in/835356 )