简体   繁体   中英

excluding certain files from a search within an array of names

This function grabs all the jpegs from folders which match the page name and prints a background image. On the homepage it searches all the sub directories and chooses one at random. What i would like is to exclude (on the homepage only) certain files which match an array of names...can anyone help?

$isHome = $this->level() == 0;

$path = '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);

In simple terms, you just need another condition in the if statement when filtering which items go into the bgimagearray for the homepage.

if ($fileinfo2->isFile() 
    && !preg_match('\.jpg$/', $fileinfo2->getFilename())
    && ! in_array($fileinfo2->getFilename, $my_blacklist_array) // added
) {

Aside: your code is a little messy and your task could likely be solved with prettier code structure; however, that would be a rewrite of your existing code rather than answering the question posed.

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