jQuerybeast
jQuerybeast

Reputation: 14490

Get first and last date from a parsed array

I have this simple loop which outputs a non-multidimensional array:

foreach($api->parse($_GET['start'], $_GET['finish']) as $item){
            $purl = parse_url($item->url());
            $data[] = array(
                        'url'   =>  $purl,
                        'publish'  =>  $item->parse_date('j M Y, g:i a'),
                        'category'  =>  htmlentities($item->cat()),
                        'status'  =>  '0',
                );

            array_push($data);
        }

var_dump($data);

How can I get the earliest and latest publish date from the above. Please note that the publish is formatted as 14 Jan 2014, 7:00 am etc.

The date will be used further to make a selection in the database:

$query_items = "SELECT * FROM `categories` WHERE
     date BETWEEN 'EARLIEST_DATE_IN_ARRAY' AND 'LATEST_DATE_IN_ARRAY' ";

Upvotes: 1

Views: 451

Answers (2)

jQuerybeast
jQuerybeast

Reputation: 14490

This is what I came up with from the untested answer of John Conde:

usort($data, function ($a, $b) {
    $date1 = (DateTime::createFromFormat('j M Y, g:i a', $a));
    $date2 = (DateTime::createFromFormat('j M Y, g:i a', $b));
    return $date2 > $date1;
});
$first = array_shift($data);
$last = array_pop($data);
$first = (new DateTime($first["publish"]))->modify('-1 day')->format('m-d-Y');
$last = (new DateTime($last["publish"]))->modify('-1 day')->format('Y-m-d H:i:s');

Upvotes: 0

John Conde
John Conde

Reputation: 219844

Untested

usort($data, function($a, $b) {
    $date1 = DateTime::createFromFormat('j M Y, G:i a', $a);
    $date2 = DateTime::createFromFormat('j M Y, G:i a', $b);
    return $date1 > $date2;
});
$first = array_shift($data);
$last = array_pop($data);

Upvotes: 3

Related Questions