-1

我在用 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>

我感谢任何解释和示例。

4

3 回答 3

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>
于 2012-06-19T05:50:44.763 回答
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>
于 2012-06-19T05:39:30.023 回答
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>
于 2012-06-19T05:52:14.513 回答