1

Im trying to figure out how to sort the array below so that past array items are sent to the end of the array staying in start_date descending order.

Edit. Id probably include a time array key value item in all arrays to sort by start_date.

[216] => Array (
    [title] => Production 1
    [start_date] => 20th Feb
    [end_date] => 23rd Feb 2015
    [ticket_link] => http://www.google.co.uk
    [writer] => Sarah Ruhl
    [thumb_image] => /files/3514/1762/4350/Biz-Bio-Pic.jpg
    [past] => 1
)

[218] => Array(
    [title] => Production 3
    [start_date] => 27th Feb
    [end_date] => 2nd Mar 2015
    [ticket_link] => www.google.co.uk
    [writer] => Sarah Ruhl
    [thumb_image] => /files/9414/1762/4351/Dan-Bio-Pic.jpg
    [past] => 1
)

[219] => Array (
    [title] => Production 4
    [start_date] => 3rd Mar
    [end_date] => 5th Mar 2015
    [ticket_link] => www.google.co.uk
    [writer] => Sarah Ruhl
    [thumb_image] => /files/4314/1762/4351/Kate-Bio-Pic.jpg
    [past] => 0
)
Rob Morris
  • 525
  • 1
  • 6
  • 20
  • 2
    this gets asked a lot, answer is `usort`. – Balázs Édes Dec 05 '14 at 11:36
  • 1
    [usort()](http://www.php.net/manual/en/function.usort.php) is the function you want. You'll need to compare by dates (timestamp or DateTime objects) rather than by date strings, so you'll need a conversion in your callback; and how do you know what year `start_date` refers to? – Mark Baker Dec 05 '14 at 11:36
  • @MarkBaker I immediately noticed this when I posted so edited my post. I'll use a time stamp for `start_date`. I've formatted the current `start_date` value so getting the year isn't a problem. How would I make sure `past` items are at the end of the array too? – Rob Morris Dec 05 '14 at 11:39

1 Answers1

2

Try this -

function checkdate($a, $b)
{
    $a = strtotime($a['start_date']);
    $b = strtotime($b['start_date']);

    if ($a == $b) {
        return 0;
    }

    return ($a > $b) ? -1 : 1;
}

function checkpast($a, $b)
{
    $a_start = strtotime($a['start_date']);
    $b_start = strtotime($b['start_date']);

    if ($a_start == b_start ) {
        return ($a['past'] > $b['past']) ? -1 : 1;
    }

}

$array = //your array

usort($array, "checkdate");
usort($array, "checkpast");
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87