Generate distinct smarty random numbers

2019-08-06 01:35发布

问题:

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)