Read all sub directories within a certain folder to display a random image
I have this code i have been using....but i need a conditional where it will read all the sub directories of /bg to select an image as opposed to a specific folder if they were on a subpage.
Heres my code so far which works perfectly for all subpages to display specific images:
//This would tell us its on the homepage if it helps:
$this->level() == 0
//This is the code so far
$path = '/home/sites/mydomain.co.uk/public_html/public/images/bg/'.$this->slug;
$homepagefile = URL_PUBLIC.'public/images/bg/'.$this->slug.'/main.jpg';
$bgimagearray = array();
$iterator = new DirectoryIterator($path);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile() && !preg_match('\.jpg$/', $fileinfo->getFilename())) {
$bgimagearray[] = "'" . $fileinfo->getFilename() . "'";
}
}
$bgimage = array_rand($bgimagearray);
?>
<div id="bg">
<div>
<table cellspacing="0" cellpadding="0">
<tr>
<td><img src="<?php echo $file.trim($bgimagearray[$bgimage], "'"); ?>" alt=""/></td>
</tr>
</table>
</div>
</div>
开发者_开发技巧Any help would be appreciated, im sure its not rocket science but ive tried a few ways and cant get my head around it.
Thanks in advance.
This is what I 've come up with. Haven't tested it though...
<?php
$isHome = $this->level() == 0
$path = '/home/sites/mydomain.co.uk/public_html/public/images/bg/';
if (!$isHome) $path .= $this->slug;
$homepagefile = URL_PUBLIC.'public/images/bg/'.$this->slug.'/main.jpg';
$bgimagearray = array();
$iterator = new DirectoryIterator($path);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile() && !preg_match('\.jpg$/', $fileinfo->getFilename()) && !$isHome) {
$bgimagearray[] = "'" . $fileinfo->getFilename() . "'";
} else if ($fileinfo->isDir() && $isHome) {
$iterator2 = new DirectoryIterator($path . $fileinfo->getFilename());
foreach ($iterator2 as $fileinfo2) {
if ($fileinfo2->isFile() && !preg_match('\.jpg$/', $fileinfo2->getFilename())) {
$bgimagearray[] = "'" . $fileinfo->getFilename() . '/' . $fileinfo2->getFilename() . "'";
}
}
}
}
$bgimage = array_rand($bgimagearray);
?>
<div id="bg">
<div>
<table cellspacing="0" cellpadding="0">
<tr>
<td><img src="<?php echo $file.trim($bgimagearray[$bgimage], "'"); ?>" alt=""/></td>
</tr>
</table>
</div>
</div>
$Directory = new RecursiveDirectoryIterator($path);
$Iterator = new RecursiveIteratorIterator($Directory);
$Images = new RegexIterator($Iterator, '/^.+\.jpg$/i', RecursiveRegexIterator::GET_MATCH);
foreach ($Images as $pathname) {
$bgimagearray[] = $pathname;
}
edit: My mistake, the regular expression must match the whole path, not just the extension. And after filtering with RegexIterator, the value is just the path, not a fileinfo object. I've edited the above code to fix it. I tested this with PHP 5.3.2.
精彩评论