readdir的随机顺序

时间:2013-05-20 01:28:12

标签: php readdir

我如何修改下面的PHP代码以输出目录中的所有文件,但是每次重新加载页面时,它们会以随机顺序放置?

if ($handle = opendir("files/slideshow/")) {
    while (false !== ($slide = readdir($handle))) {
        if ($slide != "." && $slide != "..") {
            echo "<img style=\"background:url('/files/slideshow/{$slide}');background-repeat:no-repeat;\" src=\"/files/images/i.png\"/>";
            $value = "1";
        }
    }
    closedir($handle);
}

1 个答案:

答案 0 :(得分:3)

使用glob更短的方式添加数组shuffle

$files = glob('files/slideshow/*'); // or even 'files/slideshow/*.png'
shuffle($files); 
foreach ($files as $slide)
    {
    echo "<img style=\"background:url('/files/slideshow/{$slide}');background-repeat:no-repeat;\" src=\"/files/images/i.png\"/>";
    $value = "1";
    }