【问题标题】:Show several words randomly with php用php随机显示几个单词
【发布时间】:2018-03-11 20:15:21
【问题描述】:

在我的网站上加载页面时,我需要显示自动字词。我设法显示了一个词,但我看不到一个。重要的是这些词不要重复。

我有这个代码,我在其中指定每个单词。

<?php


$randomThings = array(
    'random thing 1',    
    'random thing 2',    
    'random thing 3',    
    'random thing 4',    
    'random thing 5',    
    'random thing 6',    
    'random thing 7 ',    
);

?>

最后,我将这段代码粘贴到我想要显示的位置。

<?php echo $randomThings[mt_rand(0,count($randomThings)-1)]; ?>

正如我所说,一个词正确地显示给我,但我想显示多个。

非常感谢,对不起我的英语

【问题讨论】:

    标签: php random count words


    【解决方案1】:

    这里是sn-p,在rand_keys中提供元素的数量作为第二个参数:

    <?php
      $input = array(
        'random thing 1',    
        'random thing 2',    
        'random thing 3',    
        'random thing 4',    
        'random thing 5',    
        'random thing 6',    
        'random thing 7 ',    
      );
      $rand_keys = array_rand($input, 2);
      echo $input[$rand_keys[0]];
      echo $input[$rand_keys[1]];
    ?>
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      <?php echo array_shift( $randomThings ); ?>
      

      array_shift() 方法获取数组的第一个元素并将其从数组中取出。

      如果你想让它随机化,你可以在你的数组上使用shuffle() 函数在执行array_shift 之前对其进行洗牌。

      这是shuffle() 的 php 文档 这是array_shift()的php文档

      【讨论】:

        【解决方案3】:

        只需 shuffle,然后 pop 或 shift:

        <?php
        
        $things =
        [
            'The early bird catches the worm.',
            'Two wrongs don\'t make a right.',
            'Better late than never.'
        ];
        
        shuffle($things);
        
        while($item = array_pop($things))
            echo $item, "\n";
        

        示例输出:

        Better late than never.
        The early bird catches the worm.
        Two wrongs don't make a right.
        

        或者制作一个生成器:

        $generator = function($things) {
            shuffle($things);
            return function() use (&$things) {
                return array_pop($things);
            };
        };
        
        $thing = $generator($things);
        echo $thing();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-16
          • 1970-01-01
          • 1970-01-01
          • 2018-09-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多