php - Sort array of strings which may containing day and abbreviated month names
I want to sort an array in an ascending direction, but a normal sort approach will not respect the optionally occurring day and month substrings. The strings containing "Feedback" must be sorted by month then day as they appear on the calendar.
Not evennatsort()
will respect the months as I require.
Example array:
$array = [
"Feedback 13 okt",
"Feedback 11 okt",
"Feedback 12 okt",
"Sweet",
"Feedback 9 okt",
"Feedback 6 okt",
"Feedback 8 jun",
"Fixes",
"Realisation",
"Feedback 22 mar",
"Do something",
"Feedback 3 maj",
"Feedback 1 dec",
];
Desired result:
[
'Do something',
'Feedback 22 mar',
'Feedback 3 maj',
'Feedback 8 jun',
'Feedback 6 okt',
'Feedback 9 okt',
'Feedback 11 okt',
'Feedback 12 okt',
'Feedback 13 okt',
'Feedback 1 dec',
'Fixes',
'Realisation',
'Sweet',
]
Answer
Solution:
You should use usort() to implement your own comparison function which first compares two strings without any numbers (use preg_replace('/\d+/', '', $str) for this), and then, if the two strings compared as equal, use strnatcmp() to compare the strings (including numbers) in a natsort() way.
Answer
Solution:
Oddly, it seems my interpretation of the required sorting logic is more in-depth than the asker's.
I see the rules as:
Code: (Demo)
Output:
By using the "Elvis operator" (
?:
), subsequent tiebreaker processes are only executed if necessary. This is best practice and offers best performance.Alternate syntax for the above approach leveraging the
$mmm
lookup array: (Demo)If comfortable with regex, make a single pass over the array to make a modified version of the strings which can be sorted naturally (again leveraging the
$mmm
lookup array).Code: (Demo)
Answer
Solution:
You can create a
DateTime
from the date part and sort the dated entries chronologically inusort
. I was not able to get my locale settings right to work with your language so I had to edit the data to use English month abbreviations. I assume you have your PHP properly configured for your locale so this should work on your system with your data.So with the following
$array
value:After calling the
usort
function abovevar_export($array);
will output the following:See it working here: https://onlinephp.io/c/dc5d6