1
mboyden
Sorting Arrays in Smarty Templates
  • 2009/1/16 18:21

  • mboyden

  • Moderator

  • Posts: 484

  • Since: 2005/3/9 1


Sometimes I've wanted to override the sort order of an array of information. That used to mean I had to go into the PHP code, but no longer. Here are instructions on how to define your own sort order within your templates using Smarty. Many thanks for this Smarty Forums posting on doing an array sort.

First, you have to create the Smarty Function. Create a new file XOOPS_ROOT/class/smarty/xoops_plugins/modifier.sortby.php with the following content:

/**
 * modifier.sortby.php - 2005-08-19
 * ------------------------------------------------------------------
 * Smarty Plugin - Array Sort
 * Sorts an array by supplied fields
 * by cablehead, messju and pscs on Smarty Forums
 * orig by dholmes at jccc d0t net - from http://au.php.net/function.uasort
 */

function array_sort_by_fields(&$data,$sortby) {
    static 
$sort_funcs = array();
    if (empty(
$sort_funcs[$sortby])) {
        
$code "$c=0;";
        foreach (
split(',',$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 ( $a['$key'] > $b['$key']) return $d * 1;n";
                
$code .= "if ( $a['$key'] < $b['$key']) return $d * -1;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 given field
function smarty_modifier_sortby($arrData,$sortfields) {
    
array_sort_by_fields($arrData,$sortfields);
    return 
$arrData;
}
?>

Then you just just change your foreach loop to look like this:
<{foreach from=$array|sortby"field1,#field2,-field3,-#field4" item=fielda key=fieldb}>
where '#' means sort numerically and '-' means to sort descending instead of ascending.

Hey, it works for me, so maybe it'll work for you. Post here if you have problems and I'll monitor this thread.
Pessimists see difficulty in opportunity; Optimists see opportunity in difficulty. --W Churchill

XOOPS: Latest | Debug | Hosting and Web Development

2
Anonymous
Re: Sorting Arrays in Smarty Templates
  • 2009/1/16 22:17

  • Anonymous

  • Posts: 0

  • Since:


Hello mboyden,

Where we should use this function ? any example ?

3
mboyden
Re: Sorting Arrays in Smarty Templates
  • 2009/1/16 23:15

  • mboyden

  • Moderator

  • Posts: 484

  • Since: 2005/3/9 1


Apologies for not being clear. A site designer would call the function from within any smarty template by using the sortby smarty modifier as applied to the foreach statement. Generally, it's used within a module template for something like this as I can't see it really being used in the your theme, but it could if you wanted to.

The Example
Let's say you have a list of submitted entries to display, and the $entries array is composed of $entry arrays where each $entry is composed of the variables age (number), lastName, firstName), but the array is passed to the module template in submission order. When you display it, you would normally use this code:
<{foreach from=$entries item=entry key=entry_id}>
    
// display each item entry here
<{/foreach}>

But, what if you wanted to sort that array in order by age (oldest first), then Last Name, then First Name (and the module doesn't allow you to select this)? Then you need this solution to do it "on-the-fly" in the templates.

After creating the smarty sortby modifier function that allows this to work (as described in the previous post), modify the template's foreach statement in your template to be similar to the following code:
<{foreach from=$entries|sortby"-#age,lastName,firstName" item=entry key=entry_id}>
    
// display each item entry here
<{/foreach}>

where $entries is the array of $entry which is an array with attributes age, lastName, firstName.

Does that make it clear as mud?
Pessimists see difficulty in opportunity; Optimists see opportunity in difficulty. --W Churchill

XOOPS: Latest | Debug | Hosting and Web Development

4
Anonymous
Re: Sorting Arrays in Smarty Templates
  • 2009/1/16 23:55

  • Anonymous

  • Posts: 0

  • Since:


Very Clear .. really it is smart function

5
trabis
Re: Sorting Arrays in Smarty Templates
  • 2009/1/17 0:02

  • trabis

  • Core Developer

  • Posts: 2269

  • Since: 2006/9/1 1


Clear has mud, lol!
Very nice, clever and useful, thanks!

6
Anonymous
Re: Sorting Arrays in Smarty Templates
  • 2009/1/27 19:49

  • Anonymous

  • Posts: 0

  • Since:


How we can use it with publisher module ?

http://www.xuups.com/modules/newbb/viewforum.php?forum=28


7
ghia
Re: Sorting Arrays in Smarty Templates
  • 2009/1/27 21:03

  • ghia

  • Community Support Member

  • Posts: 4953

  • Since: 2008/7/3 1


In principle you can sort all smarty arrays with it.
The only problem is that many modules offer only a limited selection of the data to the template (eg 20 records out of some hundreds or thousands). You can sort these 20, but the next page will give you also 20 sorted lines, but if you compare them to the first page, they can be (will be) intermingled. In general the first line of the second page will not follow the last one of the first page.

Login

Who's Online

436 user(s) are online (345 user(s) are browsing Support Forums)


Members: 0


Guests: 436


more...

Donat-O-Meter

Stats
Goal: $100.00
Due Date: Nov 30
Gross Amount: $0.00
Net Balance: $0.00
Left to go: $100.00
Make donations with PayPal!

Latest GitHub Commits