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.

9
  • Possible duplicate of How can I sort arrays and data in PHP? Commented Jun 3, 2019 at 22:13
  • Does the rest of the text after the number matter in the sort? If not it should just be rsort($array). Commented Jun 3, 2019 at 22:18
  • yes they are sorted actually it sort by that text I want to sort by number @Don't Panic Commented Jun 3, 2019 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? Commented Jun 3, 2019 at 22:26
  • does not work :( @Don'tPanic Commented Jun 3, 2019 at 22:30

2 Answers 2

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.