>我有一些基本的PHP代码,当用户使用表单询问时,它会从特定的图像文件夹中拉取图像。我将有许多图像文件夹,并希望生成一个随机图像而不是使用
case 'A' : echo "<a href='"Alphabet-Letters/Letters-A'">
<img src='"image/data/A/A_001.jpg'" id='"A1'" width='"70'" height='"120'" title='"A1'"/> </a>" ; break;
我的问题是,当表格由使用字母A的人处理时,该字母的图片会出现。这个的 php 代码是
if (array_key_exists('check_submit', $_POST))
{
$letters = $_POST['Comments'];
$num_letters = strlen($letters);
for($i = 0; $i < $num_letters; $i++)
{
switch ($letters[$i]) {
case 'A' : echo "<a href='"Alphabet-Letters/Letters-A'">
<img src='"image/data/A/A_001.jpg'" id='"A1'" width='"70'" height='"120'" title='"A1'" alt='"Image A'"/>
</a>" ;
break;
这只拉取了我要求的确切图像,但我在该文件夹中有数百个图像,并且想要一个更简单的代码来处理。请有人帮忙,他们给出了使用文件夹中的随机图像的建议,但这只能作为起点,而不是我已经拥有的代码。感谢您抽出宝贵时间
下面链接中发布的解决方案应该可以实现您正在寻找的功能。https://stackoverflow.com/a/4478788/1152375
所以你应该能够做这样的事情
case 'A' : echo "<a href='"Alphabet-Letters/Letters-A'">
<img src='"image/data/A/" . random_pic("folder_with_pics") . "'" id='"A1'" width='"70'" height='"120'" title='"A1'</a>";
break;
在你得到输出代码之前,你需要在一个编号数组中获取相关目录(http://php.net/manual/en/function.dir.php(中所有文件的列表。
计算数组中的项目数(http://php.net/manual/en/function.count.php(,并使用兰德的最小和最大设置随机选择一个(http://php.net/manual/en/function.rand.php(。
尝试使用
scandir
函数查找文件夹中的所有文件,然后使用 rand
函数随机选择一个:
if(!empty($_POST['check_submit']))
{
$letters = strtoupper(trim($_POST['Comments']));
$num_letters = strlen($letters);
for($i = 0; $i < $num_letters; $i++)
{
$letter = $letters[$i];
$folder = 'image/data/'.$letter;
$files = scandir($folder);
array_shift($files);
array_shift($files);
$index = rand(0, count($files) - 1);
$file = $files[$index];
echo "<a href='"Alphabet-Letters/Letters-{$letter}'">'n";
echo "<img src='"image/data/{$letter}/{$file}'" id='"{$letter}{$index}'" width='"70'" height='"120'" title='"{$letter}{$index}'" alt='"Image {$letter}'"/>'n";
echo "</a>'n";
}
}
通过使用
@Buchow_php和反复试验找到了答案。
for ($i=0; $i<$num_letters; $i++)
{
$image_num = '$image'.$i;
echo "<input type='"hidden'" name='"option[$image_num]'" value='"$skus[$i]'" />";
}
与以前的代码一起,现在它将所有图像文件放入一个数组中,以便发布到我的提交中