phparrayssortingdatemultidimensional-array

Sort a 2d array by a date column formatted as Y-m-d


I have this array

$array = array(
array(
"start" => "2013-12-22",
    "end" => "2013-12-25"
),
array(
"start" => "2013-12-30",
    "end" => "2013-12-31"
),
array(
"start" => "2013-11-28",
    "end" => "2013-11-30"
),
array(
"start" => "2014-07-12",
    "end" => "2014-07-18"
),
array(
"start" => "2014-08-01",
    "end" => "2014-08-07"
)
);

i want to short the dates based on "start" date ascending. so I use this usort to do that

function sortFunction($a, $b) {
            return strtotime($a['start']) - strtotime($b['start']);
        }

        usort($array, "sortFunction");

print_r($array);

but I got following message, and the dates not sorted.

PHP Warning:  usort() expects parameter 2 to be a valid callback, function 'sortFunction' not found or invalid function name

How to do it properly?


Solution

  • i think u define 'sortFunction' out of the scope where You call usort($array, "sortFunction");

    You have to define and implement 'sortFunction' in the same method or scope where you call usort($array, "sortFunction");

    Alternatives:

    Use this:

    usort($array,function ($a, $b) {
            return strtotime($a['start']) - strtotime($b['start']);
        });
    

    Instead of

    function sortFunction($a, $b) {
            return strtotime($a['start']) - strtotime($b['start']);
        }
    
        usort($array, "sortFunction");