简体   繁体   中英

Fetch images randomly from directory?

I am no too proficient in PHP yet and I have this code which works so far.

<?php 
$id = JRequest::getInt('id');
$dirname = "media/k2/galleries/{$id}/";
$images = glob($dirname."*.jpg");
$rand = array_rand($dirname);
?>
<?php foreach($images as $image): ?>

<li><span class="shadowborder"><img src="<?php echo $image ?>" /></span>    </li>
 <?php endforeach; ?>

I have tried to add an array, I know $images and $image should be swapped out but as you can see but I cannot get it to gel, what am I missing? Thanks!

You can use the ' Glob ' function in partnership with array_rand() to achieve this:

<img src="
    <?php
        $id = JRequest::getInt('id');
        $imagesDir = 'media/k2/galleries/{$id}/';
        $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
        $randomImage = $images[array_rand($images)];
        echo $randomImage;
    ?>
">

You can modify which file-types to 'allow' via changing (adding/removing) this part:
'*.{jpg,jpeg,png,gif}


Feel free to ask any further questions.

You can use shuffle for this:

$id = JRequest::getInt('id');
$dirname = "media/k2/galleries/{$id}/";
$images = glob($dirname."*.jpg");
shuffle($images);
?>
<?php foreach($images as $image): ?>

<li><span class="shadowborder"><img src="<?php echo $image ?>" /></span>    </li>
 <?php endforeach; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM