【问题标题】:Randomize some strings in PHP在 PHP 中随机化一些字符串
【发布时间】:2014-07-14 15:40:18
【问题描述】:

我想像这样随机化一些字符串。

默认字符串:

one,two,three,four,five,six,seven

我需要:

six,three,one,seven,two,four,five

我只需要随机排列每一个的顺序,用,分隔。

如何在 PHP 中做到这一点?

【问题讨论】:

  • 可以提供一些你已经尝试过的概念证明,即使你没有成功并且没有产生任何结果:)

标签: php string random


【解决方案1】:
$input = 'one,two,three,four,five,six,seven';
$myArray = explode(',', $input);
shuffle($myArray);
echo implode(',', $myArray);

Works like a charm.

【讨论】:

    【解决方案2】:
    // We can't shuffle a list, but we can shuffle an array.
    
    $things = array('one','two','three','four','five','six','seven');
    
    // Shuffle randomly changes the order of the array. It uses references so it doesn't
    // make a copy of the array.
    
    shuffle($things);
    
    // then to display on the screen, either
    
    foreach ($things as $thing) {
        echo $thing.'<br>';
    }
    
    // or
    
    echo implode(',', $things);
    

    【讨论】:

      【解决方案3】:

      创建两个数组。首先,放置有序列表。

      $things = array('one','two','three','four','five','six','seven');
      

      然后创建一个与 $things 数组元素个数相同的随机数数组。

      $numItems = count($things)
      for ($i = 0; $i < $numItems; $i++) {
              $randomLst[$i] = $i;
              $temparray[$i] = mt_rand(0, 1073741823);
          }
          array_multisort($temparray, SORT_ASC, $randomLst, SORT_ASC);
      

      所以现在你有了你的项目数组和一个随机的数字数组。使用随机数字数组来调用您的项目数组。像这样。

      for ($i = 0; $i < $numItems; $i++) {
         echo $things[$randomLst][i];
      }
      

      当你需要一个新的随机列表时,创建一个新的 $randomLst。

      【讨论】:

        猜你喜欢
        • 2016-03-24
        • 2010-09-28
        • 1970-01-01
        • 2015-02-20
        • 2019-08-07
        • 2015-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多