【问题标题】:How do I select a file in PHP randomly from directory? [duplicate]如何从目录中随机选择 PHP 中的文件? [复制]
【发布时间】:2015-02-10 16:06:02
【问题描述】:

我必须从 PHP 的目录中随机选择一个文件,假设有三个文件,比如说 index.php 、 a.php 和 b.php。如何确保我不选择文件 index.php 而是随机选择其他文件。 到目前为止,我有以下代码

$dir = 'uploads';
$files = glob($dir . '/*.php');
$file = array_rand($files);
echo $files[$file];

【问题讨论】:

  • ...通过在您的目录中没有 index.php 包含不应返回 index.php 的随机文件...确定吗?
  • 添加一个if来检查$files[$file]是否不等于index.php
  • 我无法移动 index.php
  • 检查应该是$dir.index.php == $files[$file]`还是index.php == $files[$file]`
  • 忘记了一个 not :D,我编辑了我之前的评论

标签: php glob


【解决方案1】:

只需构建一个数组来排除和使用array_diff()

$exclude = array("$dir/index.php");
$files = array_diff(glob("$dir/*.php"), $exclude);

【讨论】:

    【解决方案2】:

    应该这样做:

    $dir = 'uploads';
    $files = glob($dir . '/*.php');
    while (in_array($file = array_rand($files),array('index.php')));
    echo $files[$file];
    

    您可以排除该数组中包含“index.php”的其他文件名。

    仅当目录中的文件多于'index.php'时才有效。

    【讨论】:

      【解决方案3】:

      我获取随机文件的设置,也许你只需要添加文件扩展名,..但这肯定有效。

      我不喜欢array_rand,因为它会复制数组,而且会占用大量 CPU 和 RAM。

      我想出了这个结果。

      <?php
      $handle = opendir('yourdirname');
      $entries = [];
      while (false !== ($entry = readdir($handle))) {
        if($entry == 'index.php'){
          // Sorry now allowed to read this one...
        }else{
          $entries[] = $entry;
        }
      }
      
      // Echo a random item from our items in our folder.
      echo getrandomelement($entries);
      
      
      // Not using array_rand because to much CPU power got used.
      function getrandomelement($array) {
          $pos=rand(0,sizeof($array)-1);
            $res=$array[$pos];
            if (is_array($res)) return getrandomelement($res);
              else return $res;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-08-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-03
        相关资源
        最近更新 更多