How do I sort the "Timeline" array in descending date order in PHP?

Asked

Viewed 181 times

1

How to order the "Timeline" array in 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
      },      
    ],
  }
  • the die to be ordered comes so in format json?

  • Yes, I’m getting a json and I need to order it.

  • You need to get Jason full, even though the answer doesn’t change much

1 answer

1


The answer is simple, nothing complicated since the layout of your date suggests using the function 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

How this must be a array I will generate a minimum 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 example

References:

Browser other questions tagged

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