phparrayssortingdate

Sort an array of dates formatted as \i\mmdY


I have a bunch of files that are in an array

im(month)(day)(year)

im01012007

im01022006

im01022012

im01032011

im01042010

im01042012

im01052009

im01052011

im01062012

im01072008

im01072011

etc..

is there a way to sort the array so that it sorted by year then month then day?


Solution

  • You can try use usort

    $string = "im01012007.jpg,im01022006.jpg,im01022012.jpg,im01032011.jpg,im01042010.jpg,im01042012.jpg,im01052009.jpg,im01052011.jpg,im01062012.jpg,im01072008.jpg,im01072011.jpg";
    $array = explode(",", $string); // rebulding your array ;
    
    var_dump($array);
    
    usort($array, function ($a, $b) {
        $a = DateTime::createFromFormat("mdY", substr(pathinfo($a, PATHINFO_FILENAME), 2));
        $b = DateTime::createFromFormat("mdY", substr(pathinfo($b, PATHINFO_FILENAME), 2));
        return ($a == $b) ? 0 : (($a < $b) ? - 1 : 1);
    });
    
    var_dump($array);
    

    Output

    Before

    array
      0 => string 'im01012007.jpg' (length=14)
      1 => string 'im01022006.jpg' (length=14)
      2 => string 'im01022012.jpg' (length=14)
      3 => string 'im01032011.jpg' (length=14)
      4 => string 'im01042010.jpg' (length=14)
      5 => string 'im01042012.jpg' (length=14)
      6 => string 'im01052009.jpg' (length=14)
      7 => string 'im01052011.jpg' (length=14)
      8 => string 'im01062012.jpg' (length=14)
      9 => string 'im01072008.jpg' (length=14)
      10 => string 'im01072011.jpg' (length=14)
    

    After

    array
      0 => string 'im01022006.jpg' (length=14)
      1 => string 'im01012007.jpg' (length=14)
      2 => string 'im01072008.jpg' (length=14)
      3 => string 'im01052009.jpg' (length=14)
      4 => string 'im01042010.jpg' (length=14)
      5 => string 'im01032011.jpg' (length=14)
      6 => string 'im01052011.jpg' (length=14)
      7 => string 'im01072011.jpg' (length=14)
      8 => string 'im01022012.jpg' (length=14)
      9 => string 'im01042012.jpg' (length=14)
      10 => string 'im01062012.jpg' (length=14)