GuiSousa
GuiSousa

Reputation: 25

How to get the last json date

i have a json file that has items, and each item has dates, so every date size is different.

This is an example

    "History": [
      "2018-11-07",
      "2018-11-24",
      "2019-01-10",
      "2019-02-15",
      "2019-08-30",
      "2019-09-12",
      "2019-10-11"
    ],

Is possible to get only the dates before last? (ex: last is 2019-10-11, and get the 2019-09-12)

Upvotes: 0

Views: 161

Answers (2)

Razi
Razi

Reputation: 181

try this :

    $json = '{"History" : [
            "2018-11-07",
              "2018-11-24",
              "2019-01-10",
              "2019-02-15",
              "2019-09-12",
              "2019-08-30",
              "2019-10-11"
            ]
        }';

    $php_array = json_decode($json);
    echo $php_array->History[count($php_array->History) - 2];

Upvotes: 1

catcon
catcon

Reputation: 1363

I don't know whether your array is sorted so I just assume it is unsorted.

// turn your json to an array and sort it
$json = '{"History" : [
    "2018-11-07",
      "2018-11-24",
      "2019-01-10",
      "2019-02-15",
      "2019-09-12",
      "2019-08-30",
      "2019-10-11"
    ]
}';

$date = json_decode($json, true);

function sortDate($a, $b) {
    return strtotime($a) - strtotime($b);
}

usort($date['History'], 'sortDate');

print_r($date);

// get the second last item
echo $date['History'][count($date['History']) - 2];

Output

Array
(
    [History] => Array
        (
            [0] => 2018-11-07
            [1] => 2018-11-24
            [2] => 2019-01-10
            [3] => 2019-02-15
            [4] => 2019-08-30
            [5] => 2019-09-12
            [6] => 2019-10-11
        )

)

2019-09-12

Demo: https://3v4l.org/35OoR

Upvotes: 0

Related Questions