1

私はこれでいくつかの助けを使うことができます. 1 つのディレクトリからファイルのリストを取得し、それらを配列として返す必要がありますが、キーは値と同じである必要があるため、出力は次のようになります。

array( 
    'file1.png' => 'file1.png', 
    'file2.png' => 'file2.png', 
    'file3.png' => 'file3.png' 
) 

私はこのコードを見つけました:

function images($directory) {

    // create an array to hold directory list
    $results = array();

    // create a handler for the directory
    $handler = opendir($directory);

    // open directory and walk through the filenames
    while ($file = readdir($handler)) {

        // if file isn't this directory or its parent, add it to the results
        if ($file != "." && $file != "..")
        {
            $results[] = $file;
        }

    }

    // tidy up: close the handler
    closedir($handler);

    // done!
    return $results;
}

正常に動作していますが、通常の配列を返します。

誰かがこれで私を助けることができますか?

また、最後に小さなメモとして、画像ファイル (png、gif、jpeg) のみをリストする必要があります。

4

4 に答える 4

5

次の行を変更します

$results[] = $file;

$results[$file] = $file;

ファイル拡張子を制限するには、以下のようにします

$ext = pathinfo($file, PATHINFO_EXTENSION);
$allowed_files = array('png','gif');
if(in_array($ext,$allowed_files)){
    $results[$file] = $file;
}
于 2012-10-13T08:10:06.060 に答える
0

globarray_combineを使用しないのはなぜですか?

function images($directory) {
   $files = glob("{$directory}/*.png");
   return array_combine($files, $files);
}
  • glob() は、標準パターン ( *.png など) に従ってディレクトリ上のファイルを取得します。
  • array_combine() は、キーの配列と値の配列を使用して連想配列を作成します
于 2012-10-13T08:23:19.750 に答える
0

このようなものは仕事にすべきです

$image_array = [];
foreach ($images as $image_key => $image_name) {
  if ($image_key == $image_name) {
     $image_array[] = $image_name; 
  }
  return $image_array;
}
于 2012-10-13T08:11:26.977 に答える
-1

今、私のスクリプトでこれを行います

    $scan=scandir("your image directory");
$c=count($scan);
echo "<h3>found $c image.</h3>";
for($i=0; $i<=$c; $i++):
if(substr($scan[$i],-3)!=='png') continue;
echo "<img onClick=\"javascript:select('$scan[$i]');\" src='yourdirectory/$scan[$i]' />";
endfor;

このコードは、ディレクトリから png 画像のみを一覧表示します。

于 2012-10-13T08:10:57.667 に答える