【问题标题】:Limit the number of images to display php限制图片数量显示php
【发布时间】:2016-07-08 21:09:41
【问题描述】:

此代码使图像在页面内“随机”显示。

<?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 刷新页面

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

F5 刷新页面

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

F5 刷新页面

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


但是如何一次只显示两张图片呢? 示例:

image1.png image3.png

F5 刷新页面

image3.png image2.png

F5 刷新页面

image2.png image4.png

F5 刷新页面

image3.png image1.png

【问题讨论】:

标签: php


【解决方案1】:

一个简单的方法是限制迭代

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

【讨论】:

    【解决方案2】:

    使用 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】:
      $imageCounter = 0;
      foreach ($myImagesList as $displayImagesAtRandomOrder) {
        $imageCounter++;
        echo '<img src="/imagens/' . $displayImagesAtRandomOrder . '" width="200"   height="40" border="0" />';
        if (!($imageCounter % 2)) break;
      }
      

      上面的代码只会显示 2 张图片。您可以将该数字更改为您想要的任何数字。希望对您有所帮助。

      【讨论】:

        【解决方案4】:

        洗牌后,您只需循环两次,获取数组中的前两个(0 和 1)项:

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

        【讨论】:

        • 你的 i 前面没有 $
        猜你喜欢
        • 1970-01-01
        • 2018-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-02
        • 1970-01-01
        相关资源
        最近更新 更多