从PHP中的目录中随机选择一个文件


Randomly select a file from directory in PHP

所以我已经看到了这个问题的解决方案,但我的问题略有不同。

我希望文件末尾有一个字符。

例如,有一个名为imgs:的目录

imgs内容:div.png,div2.png,divb.png,divb.png

我需要从这个文件夹中随机选择一个文件,但我需要它的末尾有一个b。所以我只能上divb.png或divb.png.

如果我得到一个不以b结尾的,我需要重新选择。我目前有一些代码会给我一个超时,并且不会重新选择。

        function random_pic($dir = 'imgs'){
$files = glob($dir . '/*.png');
$file = array_rand($files);
if(substr($files[$file], -5)==$shortparam.".png"){
    return $files[$file];
    } else {
        return null;
    }
}

编辑------------------

            <?php
function random_pic() {
  $files = glob('imgs/*.png' );
  do {
    if ( isset( $file ) ) {
      unset( $files[$file] );
    }
    $file = array_rand( $files );
  } while ( ( substr( $files[ $file ], -5  != ( $shortparam . ".png" ) ) ) AND ( count( $files) > 0 ) );
  if ( count( $files ) > 0 ) {
    return $files[ $file ];
  } else {
    echo $file;
    return false;
  }
}
for ($i = 0 ; $i < 20; $k++){
        $image = random_pic();
        if($image == false){
        } else {
   // display image

出于某种原因,这种情况会超时。(致命错误:第84行的file.php中超过了10秒的最大执行时间)

谢谢你的帮助!

您可以通过混合globarray_walk()array_rand()preg_match()来实现这一点。

<?php
    function random_pic($dir='imgs', $extension=".png", $endChar="b"){
        $files      = glob($dir . "/*{$extension}");
        $matches    = array();
        array_walk($files, function($imgFile, $index) use ($extension, $endChar, &$matches) {
            $pixName        = preg_replace("#" . preg_quote($extension) . "#", "", basename($imgFile));
            if( preg_match("#" . preg_quote($endChar) . "$#", $pixName)){
                $matches[]  = $imgFile;
            }
        });
        return (count($matches))? $matches[array_rand($matches)] : null;
    }
    $randomPic = random_pic(__DIR__. "/imgs", ".png", "b");
    // OR JUST USE THE DEFAULTS SINCE THEY ARE JUST THE SAME IN YOUR CASE:
    // $randomPic = random_pic();
    var_dump($randomPic);

我显然没有您的文件和目录结构来尝试此代码,但我很有信心它会解决您的问题。

function random_pic( $dir = 'imgs' ) {
  if ( $files = glob( $dir . '/*.png' ) ) {
    do {
      if ( isset( $file ) ) {
        unset( $files[$file] );
      }
      if ( count( $files ) > 0 ) {
        $file = array_rand( $files );
      }
    } while ( ( substr( $files[ $file ], -5  != ( $shortparam . ".png" )   ) ) AND ( count( $files ) > 0 ) );
    if ( count( $files ) > 0 ) {
      return $files[ $file ];
    } else {
      return NULL;
    }
  } else {
    return NULL;
  }
}

如果没有找到任何内容,您可能需要考虑返回FALSE而不是NULL,因为它在父端更通用。