Sort Smarty Array

Submitted by:Jhon Jhon

Date added:09 July, 2011

Category: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}

Tags: sort array

Code Snippet:

<?php

function array_sort_by_fields(&amp;$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;
}

?>
 
 

Comments