0

I have data that is in a multi-dimensional array that has a date attached to it of the format '28-Jul-17'. I would like to sort my data in ascending or descending date order. I am able to sort my multi-dimensional array, but I do not know how to sort the data out. My question is, which flag should I use to in this function to get the result that I require? At the moment I am using SORT_DESC or SORT ASC and this does not sort my date out in chronological order.

I am using the following:

 array_multisort($fieldOfInterest, SORT_DESC , $arrayOfDictionary);

Sorting type flags:

SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
SORT_NATURAL
Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
tim
  • 153
  • 1
  • 2
  • 9
  • you need to use custom sort function for that – Serving Quarantine period Aug 08 '17 at 12:22
  • The default flags don't magically know how to sort some custom date format. You'll have to parse the date correctly yourself into a comparable value. → https://stackoverflow.com/a/17364128/476 – deceze Aug 08 '17 at 12:23
  • Add your array structure plz – Justinas Aug 08 '17 at 12:23
  • 1
    Step one: Convert all the dates into timestamps or DateTime objects. Step two: Sort as normal. Step three: Convert back to human-readable date format when outputting for display. – Simba Aug 08 '17 at 12:28

1 Answers1

1

You can't do it with default flags of array_multisort(), because they don't know about custom-date-formats.

Instead of it you can do something like below:-

function compare_dates($a, $b)
{
    $t1 = strtotime($a['date']);
    $t2 = strtotime($b['date']);
    return ($t1 >$t2) ? 1:-1; //changing 1 and -1 position will make it descending
}    
usort($array, 'compare_dates'); // here $array is multi-dimensional array

Output:- https://eval.in/842881 OR https://eval.in/842882

Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85