Posted By

aashvi on 12/14/10


Tagged

sort Smarty array


Versions (?)

sort smarty array


 / Published in: Smarty
 

URL: http://www.smarty.net/forums/viewtopic.php?t=1079&sid=044cd556ed67f6ee4ed47e7cdeccd3ca

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}

  1. <?php
  2.  
  3. function array_sort_by_fields(&$data, $sortby){
  4. static $sort_funcs = array();
  5.  
  6. if (empty($sort_funcs[$sortby]))
  7. {
  8. $code = "\$c=0;";
  9. foreach (explode(',', $sortby) as $key)
  10. {
  11. $d = '1';
  12. if (substr($key, 0, 1) == '-')
  13. {
  14. $d = '-1';
  15. $key = substr($key, 1);
  16. }
  17. if (substr($key, 0, 1) == '#')
  18. {
  19. $key = substr($key, 1);
  20. $code .= "if ( ( \$c = (\$a['$key'] - \$b['$key'])) != 0 ) return $d * \$c;\n";
  21. }
  22. else
  23. {
  24. $code .= "if ( (\$c = strcasecmp(\$a['$key'],\$b['$key'])) != 0 ) return $d * \$c;\n";
  25. }
  26. }
  27. $code .= 'return $c;';
  28. $sort_func = $sort_funcs[$sortby] = create_function('$a, $b', $code);
  29. }
  30. else
  31. {
  32. $sort_func = $sort_funcs[$sortby];
  33. }
  34. uasort($data, $sort_func);
  35. }
  36.  
  37. #
  38. # Modifier: sortby - allows arrays of named arrays to be sorted by a given field
  39. #
  40. function smarty_modifier_sortby($arrData,$sortfields) {
  41. array_sort_by_fields($arrData,$sortfields);
  42. return $arrData;
  43. }
  44.  
  45. ?>

Report this snippet  

You need to login to post a comment.