Flaviu Jurcan
Flaviu Jurcan

Reputation: 105

Sort a 2-D array by a column

I have the following array.

$mem = array(
1 => array(
   0 => array(
     "start" => "2016-05-16 17:00:00",
     "end" => "2016-05-16 18:00:00"
   ),
   1 => array(
     "start" => "2016-05-16 16:10:00",
     "end" => "2016-05-16 16:40:00"
)));

I want to sort it by the start value, so that

1 => array(
  "start" => "2016-05-16 16:10:00",
  "end" => "2016-05-16 16:40:00"
)

will be the first element of the array.

I tried it with usort but it didn't work.

Upvotes: 0

Views: 58

Answers (2)

callback
callback

Reputation: 4122

try the following:

function date_compare($a, $b)
{
    $t1 = strtotime($a['start']);
    $t2 = strtotime($b['start']);
    return $t1 - $t2;
}    
usort($mem[1], 'date_compare');

Upvotes: 4

KiwiJuicer
KiwiJuicer

Reputation: 1972

Try:

usort($array[1], function($a, $b) {

    if ($a["start"] == $b["start"]) 
    {
       return 0;
    }
    return ($a["start"] < $b["start"]) ? -1 : 1;

});

Upvotes: 3

Related Questions