Php从文件夹中获取jpg文件作为数组


Php get jpg file from a folder as array

帮助我从数组中的文件夹中获取文件。我正在尝试从文件夹images获取array中的所有jpg文件名。然后使用CCD_ 3随机改变css背景。

arry中文件夹中的JPG文件;

$images=array("image1.jpg", "image2.jpg");

然后使用rand随机加载图像

echo '<style>body{background:url('.$images[array_rand($images)].')no-repeat;';

将一个目录传递给scandir,以获取该目录中所有文件的数组。然后可以使用array_filter按文件扩展名过滤掉任何非图像。

    $files = scandir( '/image/path' );
    function images_only( $file )
    {
      return preg_match( '/'.(gif|jpg|png)$/i', $file );
    }
    $files = array_filter( $files, 'images_only' );

$files现在应该只包含图像路径中的图像。

glob-it

使用array_rand修复编辑

$images = glob("images/*.jpg");
// may want to verify that the $images array has elements before echoing
echo '<style>body{background:url('.$images[array_rand($images)].') no-repeat;';