2013-03-10 2 views
-1

I 이미지 갤러리를 위해 다음과 같은 코드가 있습니다논리 AND 연산자 && foreach는 PHP에서 사용

$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++; 
} 

내가 논리 AND 연산자를 통해 이들의 foreach 문을 결합해야을 & & 그래서 두 조건이 모두에 만족하는지 같은 시간. 가능한가? 여러 번 시도했지만 구문 오류가 발생합니다.

$ file 및 $ file2 변수를 완벽하게 정의해야합니다. 이는 미리보기 이미지가 이미지와 적절하게 연결되는 유일한 방법입니다.

+1

어떤 조건입니까? – Blender

+1

당신은'array_merge()를 찾고 있습니다. – mario

+0

저는 두 파일 사이에서 유지하려고하는 실제 관계가 아니라 "논리적 AND"에 대한 반복적 인 언급이 여기에 있습니다. – IMSoP

답변

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> 
    '; 
} 

}

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 
} 
+0

하지만 $ file과 $ file2가 완벽하게 정의되어야합니다. 명확한보기를 얻으려면 내 질문에 코드를 참조하십시오 – rnvipin

+0

@rnvipin 질문을 올바르게 이해하지 못했습니다, 내 대답을 편집했습니다! – Niko

+0

감사 Niko, 나는 그것을 검사 할 것이다 :) – rnvipin

1

: 각각의 썸네일 이미지에 이미지를 매핑

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

... 

doSomething($directory); 
doSomething($thumbs_directory); 
+1

실제 질문이 맞다고 생각합니다. OP는 이미지를 미리보기 이미지에 매핑하려고합니다. 그러나 두 디렉토리의 기본 이름을 서로 먼저 매핑 한 다음 array_intersect_assoc 또는 다른 것으로 매핑해야 할 수 있습니다. – mario