phparrayssortingmultidimensional-array

Sort an associative array by Y-m-d formatted keys


Does anybody have an idea how can I sort this array by key (date) in PHP?

Array
(   
    [2011-02-16] => Array
        (
            [date] => 2011-02-16
            [num] => 2
        )

    [2011-02-11] => Array
        (
            [date] => 2011-02-11
            [num] => 0
        )

    [2011-02-17] => Array
        (
            [date] => 2011-02-17
            [num] => 0
        )

    [2011-02-18] => Array
        (
            [date] => 2011-02-18
            [num] => 0
        )

)

Solution

  • Use the uasort function, which is user customizable sorting. Like this:

    function cmp($a, $b)
    {
        if ($a['date'] == $b['date'])
        {
            return 0;
        }
        return ($a['date'] < $b['date']) ? -1 : 1;
    }
    
    uasort($your_array, "cmp");