我在php中编写此代码时遇到了一些困难。我想创建一个不是背景的随机图像,我从之前的线程中学习,但我想学习如何创建一个随机图像。这是我到目前为止我只做了数组和HTML,但我的PHP代码是不完整的:
//Random Image PHP
$images = array(array("image 1" => "caption 1"),
array("image 2" => "caption 2"),
array("image 3" => "caption 3");
//HTML
<div class="image-with-caption">
<img src="image 1/<?php echo $file; ?>.jpg" />
<p id="caption"><?php echo $caption; ?></p>
</div>
我感谢任何解释&amp;实例
答案 0 :(得分:2)
<?php
//Random Image PHP
$images = array(array("image_1","caption 1"),
array("image_2","caption 2"),
array("image_3","caption 3"));
$r = mt_rand(0,count($images)-1);
?>
//HTML
<div class="image-with-caption">
<img src="images/<?php echo $images[$r][0]; ?>.jpg" />
<p id="caption"><?php echo $images[$r][1]; ?></p>
</div>
答案 1 :(得分:1)
<?php
//Random Image PHP
$images = array();
$images[0]['image'] = "image 1";
$images[0]['caption'] = "image 1";
$images[1]['image'] = "image 2";
$images[1]['caption'] = "caption 2";
$images[2]['image'] = "image 3";
$images[2]['caption'] = "caption 3";
$rand_index = mt_rand(0,2);
?>
//HTML
<div class="image-with-caption">
<img src="image 1/<?php echo $images[$rand_index]['image']."?".time(); ?>" />
<p id="caption"><?php echo $images[$rand_index]['caption']; ?></p>
</div>
答案 2 :(得分:1)
可能没有必要让数组在数组中,但如果你想这样做,你可以尝试:
//Random Image PHP
$images = array(array("image1" => "caption 1"),
array("image2" => "caption 2"),
array("image3" => "caption 3"));
$image_key = array_rand($images);
$file = key($images[$image_key]);
$caption = $images[$image_key][$file];
//HTML
<div class="image-with-caption">
<img src="images/<?php echo $file; ?>.jpg" />
<p id="caption"><?php echo $caption; ?></p>
</div>