I don't know about JS (not really my thing), but it can be done using PHP. If you really need to use JS, you may be able to re-engineer my code.
PHP Code:
/**
* An image model.
* Filename: Image.php
*/
class Image
{
private $_filename;
private $_alt;
public function __construct($filename, $alt = null)
{
$this->_filename = $filename;
if ($alt != null) {
$this->_alt = $alt;
}
}
public function getFilename()
{
return $this->_filename;
}
public function setFilename($filename)
{
$this->_filename = (string) $filename;
}
public function getAlt()
{
return $this->_alt;
}
public function setAlt($alt)
{
$this->_alt = (string) $alt;
}
}
/**
* Stores a list of Image types.
* Filename: ImageList.php
*/
class ImageList
{
private $_images = array();
/**
* Populate the image list with some images (also verifies their type).
*/
public function __construct(array $images = null)
{
if ($images != null) {
try {
foreach ($images as $image) {
$this->_typeCheckImage($image);
}
} catch (Exception $e) {
exit('Error in class \'' . __CLASS__ . '\':' . $e->getMessage());
}
$this->_images = $images;
}
}
/**
* Verifies that the given object is of type Image (using PHP's built-in type hinting).
*/
private function _typeCheckImage(Image $image)
{
return $image;
}
/**
* @return Image a random image.
*/
public function getRandomImage()
{
if (!$this->isEmpty()) {
return $this->_images[rand[0, $this->size() - 1]);
}
return null;
}
public function isEmpty()
{
if ($this->size() > 0) {
return false;
}
return true;
}
public function size()
{
return count($this->_images);
}
}
/**
* Application code
* Filename: test.phtml
*/
// Create an array with Image objects
$images = array(
new Image('image1.png'),
new Image('image2.png'),
new Image('image3.png'),
new Image('image4.png')
);
$list = new ImageList($images);
// The number of images to generate
$count = 10;
while ($count > 0) {
$image = $list->getRandomImage();
if ($image != null) {
echo '<img src="/images/' . $image->getFilename() . '"';
if ($image->getAlt() != null) {
echo ' alt="' . $image->getAlt() . '"';
}
echo ' />' . "\n";
$count -= 1;
} else {
// End the loop
$count = 0;
}
}
You should create a grid object and populate that with the images. Also, if you're worried about speed, feel free to use an object cache. (I wrote this code without testing or demoing it, so there may be some small issues with it.)
Feel free to pm me or reply if you want more details.