这是Rails中我最喜欢的助手之一(Shopify用其液态模板语言创建了到的链接)。我为WordPress编写了一个类似的函数,请欣赏:
/**
* Cycle/alternate unlimited values of a given array.
* For instance, if you call this function five times with wp_cycle(\'three\', \'two\', \'one\'),
* you will in return get: three two one three two. This is useful for loops and allows you to
* cycle classes.
* For instance, foreach ($posts as $post) { echo \'<div class="\'.wp_cycle(\'odd\',\'even\').\'">...</div>\'; }
* would alternate between <div class="odd">...</div> and <div class="even">...</div>. Neat, huh?
* You can pass any data as args and as many as you want, e.g. wp_cycle(array(\'foo\', \'bar\'), false, 5, \'silly\')
*
* @param mixed Accepts unlimited args
* @return mixed
* @author Matthew Boynes
*/
function wp_cycle() {
global $wp_cycle_curr_index;
$args = func_get_args();
$fingerprint = substr( sha1( serialize( $args ) ), 0, 7 );
if ( !is_array( $wp_cycle_curr_index) ) $wp_cycle_curr_index = array();
if ( !isset( $wp_cycle_curr_index[ $fingerprint ] ) || !is_int( $wp_cycle_curr_index[ $fingerprint ] ) ) $wp_cycle_curr_index[ $fingerprint ] = -1;
$wp_cycle_curr_index[ $fingerprint ] = ++$wp_cycle_curr_index[ $fingerprint ] % count( $args );
return $args[ $wp_cycle_curr_index[ $fingerprint ] ];
}