Reputation: 703
I have a php array as following -
$testar = array(
'3423sdfskjx' => 'January 2017',
'1233sd3dkjx' => 'December 2017',
'1534grfdbfd' => 'March 2017',
'5849dj4fodo' => 'April 2017',
'ndj3058rjei' => 'February 2017',
'lsdl39430xm' => 'September 2017',
'059dmejri30' => 'July 2017',
'mcjd923kd05' => 'November 2017',
'3409sndfk3k' => 'May 2017',
'094873uv3jj' => 'June 2017',
'7859349cmei' => 'October 2017',
'086u7n3if39' => 'August 2017');
Primarily key is a random id and value representing some month value. I need to be sort it in alphabetical order of values so that array gets reorganized where the first key value is 'January 2017', second key value is 'February 2017' and so forth. Standard use of sort/rsort/asort/ksort won't work. How do I get this array to be sorted by months based on the array element value?
Upvotes: 0
Views: 1020
Reputation: 3905
You will need to define a custom function for sorting your array
function sortByDate($a, $b) {
return strtotime($a) - strtotime($b);
}
usort($testar, 'sortByDate');
I have derived the answer from this one
Upvotes: 1
Reputation: 15
You are right that asort
won't work to sort these months in chronological order instead you will end up with them in alphabetical order. One option, if you have the ability, would be to manipulate the data to use numeric representations of the month instead of strings and then use asort
out of the box. Alternatively, you could write your own sorting function that maps the string representation of the names to a number representation and sort them that way.
Upvotes: 0