tags:

views:

615

answers:

2

Hi,

I'm using a smarty template for a multi-language website. I got an array of country that is order by country code, which is ok for the english version as country name are in the right order but no ok for other languages (for example United Kingdom stay in the "U" whereas in French it prints "Royaume Uni".

Is there a smarty function to order an array alphabetically?

+1  A: 

You need to sort the before assigning it in smarty as such:

asort($countryList);
$smarty->assign($countryList);

Use:

  • asort() to sort the array by value.
  • ksort() to sort the array by keys.
Andrew Moore
I thought he wants it sorted by value,not keys
David Archer
You don't want to sort by keys, you want to sort by values keeping association. From what I understood from original post, the key is the country code and the value is the label. array('GB' => 'United Kingdom'). My post is right.
Andrew Moore
Fair enough, downvote removed. My bad for misinterpreting the whole thing :(
karim79
A: 

You can apply a modifier to an array in Smarty like this (the @ prefix means the modifier is applied to the whole array, not each element):

$array|@some_modifier

asort() won't work as a modifier however, because it modifies the passed array and returns a boolean rather than returning a modified array. You could however define your own function and use that as a modifier, e.g.

function sort_array($array) {
    asort($array);
    return $array;   
}

Then in Smarty you can do something like

{foreach from=$array|@sort_array item=val}
    {$val}
{/foreach}
Tom Haigh