-1

I received some data from an API and I need to sort it on time (iStart) Does anyone know how to do this? This array has like 12 items in it which contains information like this:

{
    "dayOfWeek": "Monday",
    "iDate": "2017-09-25",
    "iStart": "08:30:00",
    "utils": {
        "iStart": "08:30:00",
        "iEnd": "10:00:00",
        "name": "SOME_NAME",
        "Groups": [
            "GROUP_1",
            "GROUP_2",
            "GROUP_3"
        ],
        "Classroom": ["1021"],
        "docents": ["Teacher_1"]
    },
    "id": 11
},
{
    "dayOfWeek": "Monday",
    "iDate": "2017-09-25",
    "iStart": "13:15:00",
    "utils": {
        "iStart": "13:15:00",
        "iEnd": "14:45:00",
        "name": "SOME_NAME",
        "Groups": ["GROUP_1"],
        "Classroom": ["1021"]
    },
    "id": 12
}
castis
  • 8,154
  • 4
  • 41
  • 63
OminousMusic
  • 69
  • 1
  • 8

2 Answers2

1

You can use this code.

var arr = [{
  "name": "3",
  "iStart": "08:30:00",
},{
  "name": "5",
  "iStart": "09:30:00",
},{
  "name": "1",
  "iStart": "07:30:00",
},{
  "name": "2",
  "iStart": "07:30:03",
},{
  "name": "4",
  "iStart": "09:12:03",
}]

arr.sort(function(a,b){
  var c = parseInt( a.iStart.split(':').join('')) ;
  var d = parseInt( b.iStart.split(':').join('')) ;

  return c-d;
});
Julio Ojeda
  • 767
  • 1
  • 6
  • 24
-1

You can remove ":" from the time and convert to int, this way :

"08:30:00" -> "083000" -> 83,000

will be less than

"16:02:55" -> "160255" -> 160,255

I think you can use usort this way (assuming you have json_decode'ed as a PHP array your json string):

function cmp($a, $b){
  // [...] make sure $a['iStart'] exists with isset()
  $a = (int)str_replace(':', '', $a['iStart']); // convert "08:30:00" to 83,000
  $b = (int)str_replace(':', '', $b['iStart']);
  if ($a == $b) {
      return 0;
  }
  return ($a < $b) ? -1 : 1;
}

usort($yourJsonDecoded, "cmp");

Ref usort() http://php.net/manual/fr/function.usort.php

PS: If you want to take into account the date also, do the same by removing "-" :

$a = (int) (str_replace('-', '', $a['iDate']) . str_replace(':', '', $a['iStart']))

this will do the following : "2017-05-21" and "08:30:00" -> 20,170,821,083,000

Flo
  • 356
  • 1
  • 11