Sorting a multidimensional array (PHP) - date complications and counting

I have the following array output using PHP. I need to do two things ... First, I need to sort the array so that it is printed by the most recent date. I cannot use a simple view, because the date is displayed in mm / dd / yyyy format (and not in the usual timestamp) ...

Then I need to count how many rows exist for each year. So in the example below, I need to know which is ...

  • 2 entries since 2010
  • 2 entries from 2011
  • 1 entry since 2012
  • Stop counting if 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
        )

)

      

+3


source to share


1 answer


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 the $ array array and the above code will sort it. And for counting objects, you will need to run foreach and check date('Y',strtotime($a["racer_date"]))

in that foreach which will give you a 4 digit year.

+2


source







All Articles