lundi 30 mars 2015

Random set of images using php

I have this code that I've been using to select one random image. Now I need to select four random images.


I've tried to modify the code and it does work but I can't figure out a way to prevent the same images appearing twice. My knowledge of php is basic at best.


Can anyone shed any light please?


Thanks


my code



<?php
$root = $_SERVER['DOCUMENT_ROOT'];
$path = '/_/images/banners/';

function getImagesFromDir($path) {
$images = array();
if ( $img_dir = @opendir($path) ) {
while ( false !== ($img_file = readdir($img_dir)) ) {

if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) {
$images[] = $img_file;
}
}
closedir($img_dir);
}
return $images;
}

function getRandomFromArray($ar) {
mt_srand( (double)microtime() * 1000000 );
$num = array_rand($ar);
return $ar[$num];
}

$imgList = getImagesFromDir($root . $path);

$imgA = getRandomFromArray($imgList);
$imgB = getRandomFromArray($imgList);
$imgC = getRandomFromArray($imgList);
$imgD = getRandomFromArray($imgList);
?>

<img src="<?php echo $path . $imgA ?>" alt="<?php echo ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgA)) . ' Logo'; ?>">
<img src="<?php echo $path . $imgB ?>" alt="<?php echo ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgB)) . ' Logo'; ?>">
<img src="<?php echo $path . $imgC ?>" alt="<?php echo ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgC)) . ' Logo'; ?>">
<img src="<?php echo $path . $imgD ?>" alt="<?php echo ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgD)) . ' Logo'; ?>">




Aucun commentaire:

Enregistrer un commentaire