3

I have the following output of an array using PHP. I need to do two things... First, I need to sort the array so it prints by the most recent date. I can't use a simple sort, because the date is outputted in the format mm/dd/yyyy (and not a regular time stamp) ...

Then I need to count how many rows exist for each year. So, in the example below, I would need to know that there are ...

  • 2 entries from 2010
  • 2 entries from 2011
  • 1 entry from 2012
  • Stop counting when there are no more rows

Since the year is not separate from the rest of the date digits, this also complicates things...

Array
(
    [0] => Array
        (
            [racer_date] => 11/15/2010
            [racer_race] => Test Row 4
            [racer_event] => 321
            [racer_time] => 16
            [racer_place] => 12
            [racer_medal] => 1
        )

    [1] => Array
        (
            [racer_date] => 7/15/2010
            [racer_race] => Test Row 3
            [racer_event] => 123
            [racer_time] => 14
            [racer_place] => 6
            [racer_medal] => 0
        )

    [2] => Array
        (
            [racer_date] => 7/28/2011
            [racer_race] => Test Row
            [racer_event] => 123
            [racer_time] => 10
            [racer_place] => 2
            [racer_medal] => 2
        )

    [3] => Array
        (
            [racer_date] => 10/9/2011
            [racer_race] => Test Row 2
            [racer_event] => 321
            [racer_time] => 12
            [racer_place] => 3
            [racer_medal] => 3
        )

    [4] => Array
        (
            [racer_date] => 10/3/2012
            [racer_race] => World Indoor Championships (final)
            [racer_event] => 400m
            [racer_time] => 50.79
            [racer_place] => 1
            [racer_medal] => 1
        )

)
DJG
  • 31
  • 2

1 Answers1

2
function cmp($a, $b)
{
    if (strtotime($a["racer_date"]) == strtotime($b["racer_date"])) {
        return 0;
    }
    return (strtotime($a["racer_date"]) < strtotime($b["racer_date"])) ? -1 : 1;
}

usort($array, "cmp");

call your array $array, and above code will sort it.. And to count entities you'll need to run foreach and check date('Y',strtotime($a["racer_date"])) in that foreach which will give you year in 4 digit..

Rajat Singhal
  • 11,234
  • 5
  • 38
  • 56