2011-11-04 70 views
1

我嘗試編寫一個函數,返回一個jQuery圖像滑塊的圖像數組。PHP讀取目錄和返回數組與相關圖像鏈接的路徑

現在我在獲得正確的邏輯代碼方面陷入困境。我在想整個結構是錯的嗎? 我可以得到1個文件的正確路徑,但相關文件的數組似乎不起作用。

##info past to the function: 
$id = '11101'; 
$dir = "myimgdir/"; 
$thumbs = 'TN'; 
$medium = 'M'; 

##the files in the dir are named like this: 
11101x1xTN //thumbnail 
11101x2xTN 
11101x3xTN 
11101x1xM //some img but in medium size 
11101x2xM 
11101x3xM 

所以:

$dir = "$dir$id/";  
$get_opts = array($thumbs, $medium); 

// array to hold return value 
$retval = array(); 

    //full dir 
    $fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir"; 

$d = @dir($fulldir) or die("getImages: Failed opening directory $dir for reading"); 
while(false !== ($entry = $d->read())) { 

    $fullpath = escapeshellarg("$fulldir$entry"); 
    $file_extension = end(explode('.', $fullpath)); 
    $file_name = basename($entry, $file_extension); 


####here I get stuck 
    foreach ($get_opts as $get_opt) {   
     if (strpos($file_name, $get_opt)) { //so 11101x1xTN gontains TN 
      $retval[] = array( 
       'TN'  => "/$dir$entry", 
       'TNsize' => getimagesize("$fulldir$entry"), 

       ####how to return the medium path as well (11101x1xM) 
       'M' => "/$dir", 
      ); 
     }   
    } 



} 

$d->close();  
return $retval; 
+0

爲什麼'$ fullpath = escapeshellarg(「$ fulldir $ entry」);'?只是好奇 –

回答

0

這似乎像是一個完美的機會使用PHPs glob() function

<?php 
$thumbs = glob('*TN*'); 
foreach ($thumbs as $filename) { 
    $image_path = '/' . $dir . $filename; 
    $medium_image_path = str_replace('TN', 'M', $image_path); 
    if(!is_file($medium_image_path)) { 
     $medium_image_path = ''; 
    } 
    $retval[] = array( 
      'TN'  => $image_path, 
      'TNsize' => getimagesize($image_path), 
      'M' => $medium_image_path, 
     ); 
} 
?>