此代码会导致图像在页面中以“随机”方式显示。
<?php
$myImagesList = array (
'image1.png',
'image2.png',
'image3.png',
'image4.png'
);
shuffle ($myImagesList);
foreach ($myImagesList as $displayImagesAtRandomOrder) {
echo '<img src="/imagens/' . $displayImagesAtRandomOrder . '" width="200" height="40" border="0" />';
}
?>
示例:
image1.png image3.png image2.png image4.png
F5 reshesh page
image2.png image3.png image4.png image3.png
F5 reshesh page
image1.png image4.png image3.png image2.png
F5 reshesh page
image2.png image3.png image1.png image4.png
但是如何一次只显示两张图片? 例如:
image1.png image3.png
F5 reshesh page
image3.png image2.png
F5 reshesh page
image2.png image4.png
F5 reshesh page
image3.png image1.png
答案 0 :(得分:0)
一种简单的方法就是限制迭代
<?php
$myImagesList = array (
'image1.png',
'image2.png',
'image3.png',
'image4.png'
);
$count = 1; //set up our count, start at our first image
$imagesToShow = 2; //how many images we want to show
shuffle ($myImagesList);
foreach ($myImagesList as $displayImagesAtRandomOrder) {
//if we have reached our count, let's break out of our loop
if($count > $imagesToShow) { break; }
echo '<img src="/imagens/' . $displayImagesAtRandomOrder . '" width="200" height="40" border="0" />';
$count++; //increase our count each loop iteration
}
?>
答案 1 :(得分:0)
在对它们进行洗牌后,您可以在数组中的前两个(0和1)项目中循环两次:
shuffle ($myImagesList);
for ($i=0; $i<2; $i++) {
echo '<img src="/imagens/' . $myImagesList[$i] . '" width="200" height="40" border="0" />';
}
答案 2 :(得分:0)
使用for-loop
代替foreach
,只需2次迭代:
<?php
$myImagesList = array (
'image1.png',
'image2.png',
'image3.png',
'image4.png'
);
shuffle ($myImagesList);
for($index = 0; $index < 2; $index++){
echo '<img src="/imagens/' . $myImagesList[$index] . '" width="200" height="40" border="0" />';
}
?>
如果您不知道两个关键字的区别:what are the difference between for loop & for each loop in php
答案 3 :(得分:0)
$imageCounter = 0;
foreach ($myImagesList as $displayImagesAtRandomOrder) {
$imageCounter++;
echo '<img src="/imagens/' . $displayImagesAtRandomOrder . '" width="200" height="40" border="0" />';
if (!($imageCounter % 2)) break;
}
以上代码仅显示2张图片。您可以将该号码更改为您想要的任何号码。希望它有所帮助。