1

I'm doing a file explorer with Symfony 2.5 and PHP 5.3

In my Controller I return an array to my view (result of calling scandir(); on a directory)

The array contains "months". (January, February, March...) and I display it in a Bootstrap accordion.

I want to order by descending this array like:

December -> November -> October -> September ...

We can see that {{ for months in month|sort|reverse }} doesnt work here.

How can I do this please?

jkucharovic
  • 4,214
  • 1
  • 31
  • 46
Simon Delaunay
  • 145
  • 1
  • 18
  • ave you tried with reverse filter only ? would be better to sort them in your controller – t-n-y Jul 28 '17 at 09:03

2 Answers2

3

You need to sort array by index, otherwise it will sort array alphabetically:

{% set months = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'} %}

{% for month in months|reverse %}
 {{ month }}
{% endfor %}
jkucharovic
  • 4,214
  • 1
  • 31
  • 46
0

You can use the PHP function array_reverse(). It gives you the array in reverse order. So you don't have to do anything in Twig.

$input  = array(1, 2, 3);
$reversed = array_reverse($input);

Of course you have to use this function in your controller.

To order months not alphabetically but by time, see this post. PHP re-order array of month names

This question has already been answered. You just have to order them like this in your controller and you're done.

Jason Roman
  • 8,146
  • 10
  • 35
  • 40
Daniele Fois
  • 121
  • 6