2

I have a Laravel project, and I have an array like below.

array:12 [▼
  0 => "آبان 1398"
  1 => "آذر 1398"
  2 => "اردیبهشت 1398"
  3 => "اسفند 1397"
  4 => "بهمن 1397"
  5 => "تیر 1398"
  6 => "خرداد 1398"
  7 => "دی 1397"
  8 => "شهریور 1398"
  9 => "فروردین 1398"
  10 => "مرداد 1398"
  11 => "مهر 1398"
]

How can I sort it by values? For example, all records with 1398 after that 1397.

Karl Hill
  • 6,972
  • 3
  • 39
  • 64
Hassan
  • 178
  • 11
  • Possible duplicate of [How can I sort arrays and data in PHP?](https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – leveluptor Jun 03 '19 at 22:13
  • Does the rest of the text after the number matter in the sort? If not it should just be `rsort($array)`. – Don't Panic Jun 03 '19 at 22:18
  • yes they are sorted actually it sort by that text I want to sort by number @Don't Panic – Hassan Jun 03 '19 at 22:22
  • Well, `rsort($array)` will sort it in descending order by the entire string, so all the 1398s will be before the 1397s, but it will the 1398 and 1397 groups in descending order according to the rest of the string. Does that work for you, or does the sort need to be more complex? – Don't Panic Jun 03 '19 at 22:26
  • does not work :( @Don'tPanic – Hassan Jun 03 '19 at 22:30
  • Okay, how so? Can you explain more about how the rest of it should be sorted within the number groups? – Don't Panic Jun 03 '19 at 22:31
  • you konw it is persian alphabet and the first letter is '' ا '' and now it is sorted by that letter but I don't want sort by letter I just want to sort by that number after that number with letter – Hassan Jun 03 '19 at 22:33
  • Sorry I was wrong about rsort. I didn't realize the multibyte strings would affect it that way. Would this be helpful? https://stackoverflow.com/questions/7929796/how-can-i-sort-an-array-of-utf-8-strings-in-php – Don't Panic Jun 03 '19 at 22:36
  • the problem is this : I have an array with combination of letter and number I just want to sort it by its number – Hassan Jun 03 '19 at 22:40

2 Answers2

1

I couldn't figure out how to sort it with any of the locale-based methods I found, but I got it to work by just extracting the digits in a usort. There's probably a better way, but this seems to work okay.

usort($array, function($a, $b) {
    return preg_replace('/\D/', '', $b) <=> preg_replace('/\D/', '', $a);
});
Don't Panic
  • 37,589
  • 9
  • 55
  • 71
0

In Laravel way, you can use sortByDesc().

Example:

$collection = collect([5, 3, 1, 2, 4]);

$sorted = $collection->sortByDesc();

dd($sorted->values()->all()); //print sorted values.

Vikash Pathak
  • 2,897
  • 1
  • 14
  • 28