[英]How to get list of files as array, where key is the same as value?
I could use some help with this. 我可以用一些帮助。 I have to get list of files from one directory, and return them as array, but key needs to be the same as value, so output would be looking like this:
我必须从一个目录获取文件列表,并将它们作为数组返回,但键需要与值相同,因此输出将如下所示:
array(
'file1.png' => 'file1.png',
'file2.png' => 'file2.png',
'file3.png' => 'file3.png'
)
I found this code: 我找到了这段代码:
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;
}
It's working fine, but it returns regular array. 它工作正常,但它返回常规数组。
Can someone help me with this? 有人可以帮我弄这个吗?
Also small note at the end, I need to list only image files (png,gif,jpeg). 最后还要小记,我只需要列出图像文件(png,gif,jpeg)。
Change your following line 更改以下行
$results[] = $file;
To 至
$results[$file] = $file;
To limit file extension do as below 要限制文件扩展名,请执行以下操作
$ext = pathinfo($file, PATHINFO_EXTENSION);
$allowed_files = array('png','gif');
if(in_array($ext,$allowed_files)){
$results[$file] = $file;
}
Something like this should to the work 这样的事应该适合这项工作
$image_array = [];
foreach ($images as $image_key => $image_name) {
if ($image_key == $image_name) {
$image_array[] = $image_name;
}
return $image_array;
}
Why not using glob and array_combine ? 为什么不使用glob和array_combine ?
function images($directory) {
$files = glob("{$directory}/*.png");
return array_combine($files, $files);
}
now do this on my script 现在在我的脚本上执行此操作
$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;
this code only list png images from your directory. 此代码仅列出目录中的png图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.