Problems sorting an array

3

I have an array of objects:

$arrayTeste[] = array(
    "horario" =>$arr[$i]['horario'],
    "valor" =>$valorSoma,
    "nome" =>$arr[$i]['nome']
);

The time was all messed up, so I had to sort using the sort () function.

sort($arrayTeste);

Here's the result:

10:00:00 - 11:00:00 | 2

11:00:00 - 12:00:00 | 7

12:00:00 - 13:00:00 | 0

13:00:00 - 14:00:00 | 0

14:00:00 - 15:00:00 | 4

15:00:00 - 16:00:00 | 0

16:00:00 - 17:00:00 | 0

17:00:00 - 18:00:00 | 0

18:00:00 - 19:00:00 | 0

19:00:00 - 20:00:00 | 0

20:00:00 - 21:00:00 | 0

8:00:00 - 9:00:00 | 0

9:00:00 - 10:00:00 | 0

He ordered, but the problem is the times 8:00:00 - 9:00:00 and 9:00:00 - 10:00:00 it is probably because there is no number 0 in front of them, for example: 0 9:00:00; 0 8:00:00. is this the reason? to sort the time specifically, should I do differently than I did in sort ()?

    
asked by anonymous 27.07.2015 / 23:39

1 answer

2

Instead of sort() , use natsort() . From the documentation:

  

This function is an implementation of the algorithm that orders alphanumeric strings the way a human would do keeping key / value association. This is called "natural ordination." An example of the difference between this algorithm and the algorithm with which the computer sorts strings (used in sort ()).

Example:

<?php

$datas = array(
'10:00:00 - 11:00:00',
'11:00:00 - 12:00:00',
'12:00:00 - 13:00:00',
'13:00:00 - 14:00:00',
'8:00:00 - 9:00:00',
'9:00:00 - 10:00:00',
);

var_dump($datas);

natsort($datas);

var_dump($datas);

Output: Before (first vardump)

array(6) {
  [0]=>
  string(19) "10:00:00 - 11:00:00"
  [1]=>
  string(19) "11:00:00 - 12:00:00"
  [2]=>
  string(19) "12:00:00 - 13:00:00"
  [3]=>
  string(19) "13:00:00 - 14:00:00"
  [4]=>
  string(17) "8:00:00 - 9:00:00"
  [5]=>
  string(18) "9:00:00 - 10:00:00"
}

Then (second vardump)

array(6) {
  [4]=>
  string(17) "8:00:00 - 9:00:00"
  [5]=>
  string(18) "9:00:00 - 10:00:00"
  [0]=>
  string(19) "10:00:00 - 11:00:00"
  [1]=>
  string(19) "11:00:00 - 12:00:00"
  [2]=>
  string(19) "12:00:00 - 13:00:00"
  [3]=>
  string(19) "13:00:00 - 14:00:00"
}
    
27.07.2015 / 23:42