实现rand功能

时间:2011-07-14 04:25:04

标签: php function

我有以下代码部分。反正我是否可以使用php rand()函数随机显示foreach中的项目?我试过谷歌,但我很困惑如何实现它在这种情况下。

<?php
$dir = 'catalog/view/theme/default/gallery/';?>
<div id="Box">
<div id="slideShow">
<ul>
<?php foreach(glob($dir.'*.jpg') as $file) : ?>
<li><img width="370" height="480" alt="" src="<?=$file?>"/></li>
<?php endforeach; ?>
</ul>
</div>
</div>

3 个答案:

答案 0 :(得分:4)

假设您想以随机顺序显示所有图像,您可以尝试这样的事情:

<?php
    $files = glob($dir . "*.jpg");
    shuffle($files);
    foreach($files as $file):
?>
<li><img width="370" height="480" alt="" src="<?= $file ?>" /></li>
<?php
    endforeach;
?>

答案 1 :(得分:1)

我在rand()查询中使用了SELECT,然后使用foreach order by rand()它已经有效了。

答案 2 :(得分:0)

您可以将文件读入数组并使用array_rand

http://php.net/manual/en/function.array-rand.php