4

I have a php array like this:-

array(3) {
     [0]=>
      string(4) "9:30"
     [1]=>
      string(5) "15:00"
     [2]=>
      string(5) "13:00"
}

After sorting this time i am getting wrong data. i am sorting it by array_multisort function.

This is what i am getting after time is sorted

array(3) {
   [0]=>
     string(5) "03:00"
   [1]=>
     string(5) "01:00"
   [2]=>
     string(5) "09:30"
 }

This is my code

first i am converting my time to unix time by using strtotime function then sorting 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 my $totlahourdat1 array then i get this:

array(3) {
   [0]=>
    int(1500535800)
   [1]=>
    int(1500555600)
   [2]=>
    int(1500548400)
 }

My result should be like:

array(3) {
  [0]=>
    string(4) "9:30"
  [1]=>
    string(5) "13:00"
  [2]=>
    string(5) "15:00"
}

Any help will be highly appreciated.

Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
Harpreet Singh
  • 804
  • 5
  • 18

4 Answers4

3

Use natsort($array) see function definition

squareCircle
  • 182
  • 11
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

Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
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);
});
Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
Jim Wright
  • 5,256
  • 1
  • 9
  • 30
1

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 م
  • 4,969
  • 2
  • 30
  • 49