3

帮我从数组中的文件夹中获取文件。我正在尝试array从文件夹中获取所有 jpg 文件名images。然后使用rand随机更改c​​ss背景。

arry 文件夹中的 JPG 文件;

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

然后使用rand随机加载图像

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

2 回答 2

4

将目录传递给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现在应该只包含来自图像路径的图像。

于 2012-08-26T22:26:13.653 回答
1

把它通通

用 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;';
于 2012-08-26T14:59:41.280 回答