Multiple random images per page, without repeat

后端 未结 1 1962
不思量自难忘°
不思量自难忘° 2021-01-27 14:28

So, I need to display 2 or 3 different images in a website, as simple parallax dividers for content.

I have an array of 4 images, so I\'ll be able to randomize without r

相关标签:
1条回答
  • 2021-01-27 14:49

    Not sure is that you want but this will give you randomized images (without repeat) on a page, every time different ones:

    <?php
        $img = array('img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png', 'img6.png');
        shuffle($img);
        for($i=0; $i<3; $i++){
            print '<img src="'.$img[$i].'"><br>';
        }
    ?>        
    

    If you want to receive one image per call, one of the possible solutions is to use session:

    image.php:

    <?php
        session_start();
        function getImage() {
            $img = array('img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png');
            shuffle($img);
            foreach($img as $key => $val) {
                if (!is_array($_SESSION['img'])) {
                    return $val;
                } elseif (count($_SESSION['img']) >= count($img)) {
                    $_SESSION['img'] = array();
                }
                if (is_array($_SESSION['img']) && !in_array($val, $_SESSION['img'])) {
                    return $val;
                }
            }
        }
    ?>
    

    page.php:

    <?php
        include 'image.php';
        for ($i = 0; $i < 3; $i++) {
            $currImg = getImage();
            $_SESSION['img'][] = $currImg;
            echo $currImg . '<br>';
        }
    ?>
    

    All displayed images are stored into SESSION variable. When all images are displayed, this SESSION var is reset and will start a new cycle.

    0 讨论(0)
提交回复
热议问题