0

Actually I have one array and I need to sort it according to date wise but unfortunately it becomes difficult for me. Can you help me out ...

I have an array like that in below

         $data = array ( 
            array('July 2015', 2 , 5, 0, ''),
            array('September 2015', 2 , 5, 0, ''),
            array('August 2015', 2 , 5, 0, ''),
            array('March 2017', 2 , 5, 0, ''),
            array('December 2015', 2 , 5, 0, ''),
            array('March 2016', 2 , 5, 0, ''),
         );

Now I want to sort this array according to date wise that start from the smallest date to bigger date like, it will becomes like that.

         $data = array ( 
            array('July 2015', 2 , 5, 0, ''),
            array('August 2015', 2 , 5, 0, ''),
            array('September 2015', 2 , 5, 0, ''),
            array('December 2015', 2 , 5, 0, ''),
            array('March 2016', 2 , 5, 0, ''),
            array('March 2017', 2 , 5, 0, ''),
         );

Can anyone help me.

Any help will be appreciated.

Thanks

John Brad
  • 447
  • 1
  • 10
  • 26

2 Answers2

1

Use the usort function and convert string dates to timestamps using strtotime:

usort($data, function ($a, $b) {
    $aTime = strtotime($a[0]);
    $bTime = strtotime($b[0]);

    if ($aTime == $bTime)
        return 0;

    return $aTime > $bTime ? 1 : -1;
});
MaGnetas
  • 4,918
  • 4
  • 32
  • 52
1
$data = array(
    array('July 2015', 2, 5, 0, ''),
    array('September 2015', 2, 5, 0, ''),
    array('August 2015', 2, 5, 0, ''),
    array('March 2017', 2, 5, 0, ''),
    array('December 2015', 2, 5, 0, ''),
    array('March 2016', 2, 5, 0, ''),
);

uasort($data, function($a,$b){ 
    if(strtotime($a[0]) == strtotime($b[0])) 
    { 
        return 0;
    } 
    return strtotime($a[0]) < strtotime($b[0]) ? -1 : 1;
 });

print_r($data);

Or the simplest way as DECEZE said

uasort($data, function($a,$b){ 
   return strtotime($a[0]) - strtotime($b[0]);
});

DEMO

DEMO SUGGESTED BY DECEZE

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54