# Posted By

aashvi on 12/14/10

# Statistics

Viewed 1695 times
Favorited by 0 user(s)

# sort smarty array

/ Published in: Smarty

How to sort array in smarty template?

>> Create sort modifier file and save it in smarty / plugins with
modifier.sortby.php name
use this modifier in smarty template like...
{foreach item=item key=key from=\$users|@sortby:"firstname"}
{\$item.id}-{\$item.firstname}
{/foreach}

Copy this code and paste it in your HTML
`<?php function array_sort_by_fields(&\$data, \$sortby){      static \$sort_funcs = array();     if (empty(\$sort_funcs[\$sortby]))    {        \$code = "\\$c=0;";        foreach (explode(',', \$sortby) as \$key)        {           \$d = '1';              if (substr(\$key, 0, 1) == '-')              {                 \$d = '-1';                 \$key = substr(\$key, 1);              }              if (substr(\$key, 0, 1) == '#')              {                 \$key = substr(\$key, 1);               \$code .= "if ( ( \\$c = (\\$a['\$key'] - \\$b['\$key'])) != 0 ) return \$d * \\$c;\n";              }              else              {               \$code .= "if ( (\\$c = strcasecmp(\\$a['\$key'],\\$b['\$key'])) != 0 ) return \$d * \\$c;\n";            }        }        \$code .= 'return \$c;';        \$sort_func = \$sort_funcs[\$sortby] = create_function('\$a, \$b', \$code);    }    else    {        \$sort_func = \$sort_funcs[\$sortby];    }       uasort(\$data, \$sort_func);   } ## Modifier: sortby - allows arrays of named arrays to be sorted by a given field#function smarty_modifier_sortby(\$arrData,\$sortfields) {   array_sort_by_fields(\$arrData,\$sortfields);   return \$arrData;} ?>`