Smarty multiple random numbers list
is there a开发者_StackOverflowny smart way to post random numbers (e.g. 1-4) in a list by using the smarty tpl-engine?
standart list sorted 1-5:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
Here's my solution (PHP):
<ul>
{foreach from=randomNumbers}
<li>{smarty.randomNumbers}</li>
{/foreach}
</ul>
modified list sorted 1-5 (random):
<ul>
<li>3</li>
<li>2</li>
<li>5</li>
<li>1</li>
<li>4</li>
</ul>
I've really tested nearly everything, but I do only need a smart & small solution for this :-)
Kind Regards, Heinrich
You can use the rand() function from php in smarty. Pass the parameter as the number of times you run the loop and you should be done.
You could do something really dirty like this:
<ul>
{foreach from=0|range:4|@array_rand:5 item=i}
{assign var=i value=$i+1}
<li>{$i}</li>
{/foreach}
</ul>
Edit
As you said array_rand()
no longer shuffles results. You can't really use shuffle()
easily because it does not return the shuffled array - you could do something like this though:
//somewhere in an included PHP file
function shuffle_array($array){
shuffle($array);
return $array;
}
{*template *}
<ul>
{foreach from=1|range:5|@shuffle_array item=i}
<li>{$i}</li>
{/foreach}
</ul>
ok, it seems to be a PHP-Problem. Since the last PHP versions, array_rand isn't random any more. I've tried to add something like this
|shuffle
or
shuffle();
to tom's smarty-code,
but without success >_<
...
精彩评论