-1

我有以下图片库代码:

$directory = 'some path';
$thumbs_directory = 'some path';
foreach (glob($directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $file) 
foreach (glob($thumbs_directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $file2)
{

    if($file=='.' || $file == '..') continue;
    $file_parts = explode('.',$file);
    $ext = strtolower(array_pop($file_parts));
    $title = basename($file);
    $title = htmlspecialchars($title);
    $title = str_replace("_"," ",$title);
    $nomargin='';
    if(($i+1)%4==0) $nomargin='nomargin';
    echo '
    <div class="pic '.$nomargin.'" style="background:url('.$file2.') no-repeat 50% 50%;">
    <a href="'.$file.'" title="'.$title.'" target="_blank">'.$title.'</a>
    </div>';
    $i++;
}

我需要通过逻辑与运算符 && 组合这些 foreach 语句,以便同时满足两个条件。可能吗 ?我尝试了很多次,但总是以语法错误告终。

请注意,我需要完美定义 $file 和 $file2 变量。这只是缩略图与图像正确关联的唯一方式。

4

3 回答 3

1

根据您的描述,如果您想遍历两个目录中存在的图像文件,您应该考虑使用 php 的array_intersect()

$directory = 'some path';
$thumbs_directory = 'some path';

$files_in_dir1 = glob($directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$files_in_dir2 = glob($thumbs_directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE);

$files_in_both_dirs = array_intersect($files_in_dir1, $files_in_dir2);

foreach ($files_in_both_dirs as $filename) {
  // Code
}
于 2013-03-10T23:16:03.427 回答
1

能不能简单的把肉肉的逻辑重构成一个通用的函数,然后调用两次?

例如:

function doSomething($directory) {
    foreach (glob($directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $file) {
        /* Whatever */
    }
}

...

doSomething($directory);
doSomething($thumbs_directory);
于 2013-03-10T23:10:45.773 回答
1

要将图像映射到各自的缩略图,我宁愿选择不同的方法:

$directory = 'some path';
$thumbs_directory = 'some path';

// Get all images
$images = glob($directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE);

// Iterate over all images
foreach ($images as $image) {
    // Construct path to thumbnail
    $thumbnail = $thumbs_directory .'/'. basename($image);

    // Check if thumbnail exists
    if (!file_exists($thumbnail)) {
        continue; // skip this image
    }

    // .. continue as before

    echo '
        <div class="pic '.$nomargin.'" style="background:url('.$thumbnail.') no-repeat 50% 50%;">
        <a href="'.$image.'" title="'.$title.'" target="_blank">'.$title.'</a>
        </div>
    ';
}

}

于 2013-03-10T23:11:33.570 回答