2010-06-02 172 views
0

我想知道是否有以随机顺序阅读目录的方法。PHP:读取所有文件,但随机?

用下面的代码我正在运行目录的大拇指,它在我的网站上打印图像。然而,他们总是按字母顺序阅读,我不知道是否有办法随机做这件事?

<?php 
$path = 'thumbs'; 
if ($handle = opendir($path)) { 
    while (false !== ($file = readdir($handle))) { 
     if ($file != '.' && $file != '..' && $file != '.DS_Store' && $file != 'Thumbs.db') { 
       print "<img class='thumb' src='$path/$file'/>"; 

     } else { 
      //no proper file 
     } 
    } 
    closedir($handle); 
} 
?> 

感谢您的建议!

关于

+0

HTTP:/ /www.php.net/manual/en/function.readdir.php#90770 – Sarfraz 2010-06-02 07:23:01

回答

3

为什么不把结果放在数组中,然后随机洗牌数组?

0

而不是打印图像把文件名称放入一个数组中,当循环结束时对其进行随机打印,并在此之后打印另一个循环以打印值。

0

尝试使用此功能:

function getDirContent($dir='./'){ 
if (is_dir($dir)) { 
    $fd = @opendir($dir); 
    while (($part = @readdir($fd)) == TRUE) { 
     clearstatcache(); 
     $dir_array[] = $part; 
    } 
    if($fd == TRUE) { 
     closedir($fd); 
    } 
    if (is_array($dir_array)) { 
     shuffle($dir_array); 
     return $dir_array; 
    } else { 
     Return FALSE; 
    } 
} 

}

0
$files = glob("$path/*.[JjGg][PpIi][GgFf]"); 
shuffle($files); 
0

我知道这是一个老的文章,但这些代码可能有人会有所帮助搜索:

$dir = 'path/to/dir'; 
    if ($handle = opendir($dir)) { 
    $files = array(); 
    while (false !== ($file = readdir($handle))) { 
    if ($file != '.' && $file != '..') { 
    array_push($files,$file); 
} 
} 
    closedir($handle); 
    shuffle($files); // <- THIS DID THE TRICK** 
    foreach($files as $file) { 
    echo $file; 
    } 
}