Problems sorting an array

Asked

Viewed 70 times

3

I have an array of objects:

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

The schedule was all cluttered, so I ordered using the Sort function().

sort($arrayTeste);

That is 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 schedules 8:00:00 - 9:00:00 and 9:00:00 - 10:00:00, it’s probably because there’s no number 0 in front of them, for example: 09:00:00; 08:00. would this be the reason? to specifically order the time, I must do differently from what I did on Sort()?

  • 1

    I noticed that you’ve been asking some questions lately @chocolatemontana, but you haven’t registered for Stack Overflow. I think it’s important that you register and participate more actively in the community. Make a [tour] and see what the community proposal and do not forget to mark the answers that solve your question as accepted answer.

  • The problem is that you are ordering strings and not numbers... I believe the most ideal for this case is the function usort or convert all times to a timestamp (using the same day for all) so that sorting can be done using integer numbers.

1 answer

2

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

This function is an implementation of the algorithm that sorts alphanumeric strings in the way a human would maintain 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);

Exit: 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"
}
  • didn’t work out, how do you do it? natsort($arrayTeste); ? natsort($arrayTeste['horario']) ?

  • @chocolatemontana see example: http://3v4l.org/SaLJQ

Browser other questions tagged

You are not signed in. Login or sign up in order to post.