nic*_*888 1 php arrays file list
我可以用一些帮助.我必须从一个目录获取文件列表,并将它们作为数组返回,但键需要与值相同,因此输出将如下所示:
array(
'file1.png' => 'file1.png',
'file2.png' => 'file2.png',
'file3.png' => 'file3.png'
)
Run Code Online (Sandbox Code Playgroud)
我找到了这段代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但它返回常规数组.
有人可以帮我弄这个吗?
最后还要小记,我只需要列出图像文件(png,gif,jpeg).
更改以下行
$results[] = $file;
Run Code Online (Sandbox Code Playgroud)
至
$results[$file] = $file;
Run Code Online (Sandbox Code Playgroud)
要限制文件扩展名,请执行以下操作
$ext = pathinfo($file, PATHINFO_EXTENSION);
$allowed_files = array('png','gif');
if(in_array($ext,$allowed_files)){
$results[$file] = $file;
}
Run Code Online (Sandbox Code Playgroud)