【发布时间】:2012-02-09 00:04:48
【问题描述】:
我想从一个目录中随机加载图像,并在某处有一个刷新整个页面的按钮。这是我现在拥有的当前代码:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
}
?>
问题是它一次加载所有 400,000 张图像。我只想加载 30 个。目录中的 30 张随机图像。我尝试查找一些代码,例如将上面的代码修改为:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
if (++$i == 2) break;
}
?>
但它似乎什么也没做。所以如果有人可以帮助我从该目录中随机获取 30 张照片以加载并具有某种类型的重新加载按钮,那将是非常有帮助的。
提前谢谢你
【问题讨论】:
-
$i显然是一个字符串,所以++$i没有意义。随后的相等比较也不起作用。