Reputation: 281
I am trying to figure out the best way, using PHP, to pull a random image from multiple sub-folders on my site. I would use the RecursiveDirectoryIterator to iterate through the subfolders and extract images, but am wondering how to handle the randomisation and how to do it efficiently. Any advice on how to go about this?
Upvotes: 1
Views: 1498
Reputation: 543
function get_images($root) {
$r = array();
foreach(glob("$root/*") as $n) {
if (is_dir($n)) {
$r = array_merge($r, get_images($n));
} else {
$r[] = $n;
}
}
return $r;
}
$files = get_images('foo');
shuffle($files);
echo $files[0];
Upvotes: 3
Reputation: 4042
Load all the full $path
s into an $array
and select mt_rand(0, count($array)-1)
.
You might want to cache your list as long as it does not change, to avoid re-iterating over your directories.
Upvotes: 0
Reputation: 9319
Create a random number for the iteration endpoint (while $i < 10). Before this you can create another random session to choose the directory.
Read all images into an array then pick a random index.
Upvotes: 3