How to sort array "timeline" by descending date order in PHP?

0

How to sort array "timeline" by descending date order in PHP?

"bookingAnalysis": {
    "timeline": [
      {
        "date": "2017-12-02",
        "count": 1,
        "peopleCount": 2
      },
      {
        "date": "2017-12-01",
        "count": 1,
        "peopleCount": 4
      },
      {
        "date": "2017-12-08",
        "count": 1,
        "peopleCount": 4
      },     
      {
        "date": "2017-12-29",
        "count": 1,
        "peopleCount": 2
      },
      {
        "date": "2018-01-12",
        "count": 1,
        "peopleCount": 2
      },
      {
        "date": "2018-01-19",
        "count": 1,
        "peopleCount": 2
      },
      {
        "date": "2018-01-21",
        "count": 1,
        "peopleCount": 2
      },
      {
        "date": "2018-01-27",
        "count": 1,
        "peopleCount": 2
      },
      {
        "date": "2018-01-10",
        "count": 1,
        "peopleCount": 6
      },      
    ],
  }
    
asked by anonymous 14.06.2018 / 17:40

1 answer

0

The answer is simple, nothing complicated since the layout of your date suggests using the strtotime as follows, a basic example :

<?php

var_dump(strtotime("1999-01-01") > strtotime("1999-01-02")); // false
var_dump(strtotime("1999-01-02") > strtotime("1999-01-01")); // true

As this should be a array information I will generate a minimal example, with the function usort with strtotime :

<?php

$data = array(
    array("date" => "2018-01-21", "count" => 1, "peopleCount"=> 2),
    array("date" => "2018-01-22", "count" => 1, "peopleCount"=> 3),
    array("date" => "2018-01-19", "count" => 1, "peopleCount"=> 4),
    array("date" => "2018-01-25", "count" => 1, "peopleCount"=> 5)
    );


usort($data, function($d1, $d2){
    $t1 = strtotime($d1['date']);
    $t2 = strtotime($d2['date']);
    if ($t1 === $t2) return 0;
    return ($t1 > $t2) ? -1 : 1;
});

var_dump($data);

Check the Online Sample

14.06.2018 / 18:10