Generate distinct smarty random numbers

。_饼干妹妹 提交于 2019-12-13 02:19:42

问题


I'm using smarty v2.6 and I want to generate random distinct numbers. I'm looking for an efficient, fast way to do it using already provided Smarty functions. This is my code for generating 5 random numbers (but not distinct):

{assign var=min value=1}{assign var=max value =5}
{section name=val start=$min loop=$max+1}
{assign var=random value=1|mt_rand:15}
{$random}
{/section}

回答1:


if you really need to do it in smarty templates

method 1

{assign var="distinct_numbers" value=array_fill(1,15,'x')}
{assign var="distinct_numbers" value=array_keys($distinct_numbers)}
{assign var="x" value=shuffle($distinct_numbers)}

{* result *}

{foreach from=$distinct_numbers item="value"}
    {$value} |
{/foreach}


1 | 7 | 3 | 10 | 4 | 8 | 6 | 14 | 13 | 12 | 2 | 5 | 11 | 9 | 15 | 

method 2

  • array_fill()
  • array_keys()
  • array_rand() + unset() instead shuffle()



回答2:


You're approaching the problem from the wrong point of view.

Smarty is used to display data, with a very limited set of instructions to manipulate them. Since we're talking about logic here you should generate your random unique numbers elsewhere and then pass the result to the Smarty engine.

Therefore, assuming you're using PHP, try something like this:

$min = 1;
$max = 100;
$items_to_pick = 5;
$values = array();

for($i=$min; $i<= $max; ++$i){
    $values[] = $i;
}

shuffle($values) //see PHP doc http://www.php.net/manual/en/function.shuffle.php

$result = array_slice($values, 0, $items_to_pick);

$smarty->assign('random_numbers', $result);

And in your template file:

{foreach from=$random_numbers item=random}
    {$random}
{/foreach}

You should always try to separate content from presentation. Smarty shouldn't care about the values it's passed. (outside simple checks to see if you should display something or not, in my opinion)



来源:https://stackoverflow.com/questions/23830240/generate-distinct-smarty-random-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!