get random value from a PHP array, but make it unique

后端 未结 9 1065
挽巷
挽巷 2020-12-16 19:44

I want to select a random value from a array, but keep it unique as long as possible.

For example if I\'m selecting a value 4 times from a array of 4 elements, the s

相关标签:
9条回答
  • 2020-12-16 20:12

    http://codepad.org/sBMEsXJ1

    <?php
    
        $array = array('abc', 'def', 'xyz', 'qqq');
    
        $numRandoms = 3;
    
        $final = array();
    
        $count = count($array);
    
        if ($count >= $numRandoms) {
    
            while (count($final) < $numRandoms) {
    
                $random = $array[rand(0, $count - 1)];
    
                if (!in_array($random, $final)) {
    
                    array_push($final, $random);
                }
            }
        }
    
        var_dump($final);
    
    ?>
    
    0 讨论(0)
  • 2020-12-16 20:15

    Php has a native function called shuffle which you could use to randomly order the elements in the array. So what about this?

    $arr = ('abc', 'def', 'xyz', 'qqq');
    
    $random = shuffle($arr);
    
    foreach($random as $number) {
        echo $number;
    }
    
    0 讨论(0)
  • 2020-12-16 20:16
    $isShowCategory = array();
    for ($i=0; $i <5 ; $i++) { 
       $myCategory = array_rand($arrTrCategoryApp,1); 
       if (!in_array($myCategory, $isShowCategory)) {
          $isShowCategory[] = $myCategory;
    
          #do something 
    
       }
    }
    
    0 讨论(0)
  • 2020-12-16 20:29

    How about shuffling the array, and popping items off.

    When pop returns null, reset the array.

    $orig = array(..);
    $temp = $orig;
    shuffle( $temp );
    
    function getNextValue()
    {
      global $orig;
      global $temp;
    
      $val = array_pop( $temp );
    
      if (is_null($val))
      {
        $temp = $orig;
        shuffle( $temp );
        $val = getNextValue();
      }
      return $val;
    }
    

    Of course, you'll want to encapsulate this better, and do better checking, and other such things.

    0 讨论(0)
  • 2020-12-16 20:31

    If you do not care about what particular values are in the array, you could try to implement a Linear Congruential Generator to generate all the values in the array.

    LCG implementation

    Wikipedia lists some values you can use, and the rules to select the values for the LCG algorithm, because the LCG algorith is deterministic it is guaranteed not to repeat a single value before the length of the period.

    After filling the array with this unique numbers, you can simply get the numbers in the array 1 by 1 in order.

    0 讨论(0)
  • 2020-12-16 20:32

    Easy and clean:

    $colors = array('blue', 'green', 'orange');
    $history = $colors;
    
    function getColor($colors, &$history){
        if(count($history)==0)
            $history = $colors;
        return array_pop( $history );
    }
    
    echo getColor($colors, $history);
    
    0 讨论(0)
提交回复
热议问题