2016-07-08 108 views
0

此代碼會導致圖像以頁面內的「隨機」顯示。限制要顯示的圖像數php

<?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頁

image2.png image3.png image4.png image3.png

F5 reshesh page

image1.png image4.png image3.png image2.png

F5 reshesh頁

image2.png image3.png image1.png image4.png


但我怎麼每次只顯示兩個圖像? 例如:

image1.png image3.png

F5 reshesh頁

image3.png image2.png

F5 reshesh頁

image2.png image4.png

F5 reshesh page

image3.png image1.png

+1

在輸出所需圖像的數量後,您的循環中「break」出現。 Dupe:http://stackoverflow.com/questions/588892/can-you-exit-a-loop-in-php –

+0

[限制循環在php中運行的次數]可能的重複(http://stackoverflow.com/questions/1998204 /限制次數循環運行在PHP) –

回答

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 
} 
?> 
0

洗牌之後他們,你可以循環兩次服用前兩個(0和1)項數組中:

shuffle ($myImagesList); 
for ($i=0; $i<2; $i++) { 
echo '<img src="/imagens/' . $myImagesList[$i] . '" width="200" height="40" border="0" />'; 
} 
+1

你的我沒有$在他們面前 – ied3vil

+0

哦,是啊,PHP。對,謝謝@ ied3vil –

0

使用的for-loop代替foreach只有2 iteraction:

<?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" />'; 
} 

?> 

如果你不知道beetwen的兩個關鍵字的區別是:what are the difference between for loop & for each loop in php

0
$imageCounter = 0; 
foreach ($myImagesList as $displayImagesAtRandomOrder) { 
    $imageCounter++; 
    echo '<img src="/imagens/' . $displayImagesAtRandomOrder . '" width="200" height="40" border="0" />'; 
    if (!($imageCounter % 2)) break; 
} 

上面的代碼將只顯示2個圖像。您可以將該號碼更改爲您想要的任何號碼。希望能幫助到你。