Symfony / TWIG, Sort Array by Key

Viewed 4061

Is it possible to sort an array by key without twig extension ?

I have an array like this :

{key1 : object1, key2 : object2...)

When i use {% for t in tab|sort%}, it give me an array sort by object ID and not by the key.

No way to do this without twig extension ?

1 Answers

As far as I know, there isn't a filter to do the sort by array key.

However, in case if you need to create a filter, you can do like this in your extended Twig extensions file,

Create the function,

public function ksort($array) {
    ksort($array);        
    return $array;
}

Hook the function in available filters,

public function getFilters() {
    $this->filters['ksort'] = new \Twig_SimpleFilter('ksort', array($this, 'ksort'));        
    return $this->filters;
}

And to call the filter,

{% for a in array | ksort %}
    <h2>{{ a }}</h2>   
{% endfor %}    

Cheers

Related