Thursday, 11 September 2014

PHP: Sorting an array by value (UK formatted date string)

function cmp($a, $b)
{
    $a_int = DateTime::createFromFormat('j/m/Y', $a["date"])->getTimestamp();
    $b_int = DateTime::createFromFormat('j/m/Y', $b["date"])->getTimestamp();
    return ($a_int == $b_int) ? 0 : ($a_int < $b_int) ? 1 : -1;
}

Dead simple isn't it? I end up using this a lot so maybe it'll be of use to someone else?

Call it like this:

<?php
    usort($arr, "cmp");
?>

No comments:

Post a Comment