简体   繁体   English

如何建立目录中存在的.html文件名的索引数组?

[英]How to build an indexed array of .html filenames that exist in a directory?

I am using this php code to get all html-files in the given directory: 我正在使用此php代码来获取给定目录中的所有html文件:

$dirpath = ".....";
$filelist = preg_grep('~\.(html)$~', scandir($dirpath));

Now I want to get a specific element in the array, for example: 现在,我想获取数组中的特定元素,例如:

echo $filelist[0];

This fails. 这失败了。 In my directory there are 52 files, and count($filelist) returns '52', but to get the first element I need to use echo $filelist[3]; 在我的目录中有52个文件, count($filelist)返回'52',但是要获取第一个元素,我需要使用echo $filelist[3]; The last item gets addresses by the index 54. What is this? 最后一项通过索引54获取地址。这是什么? Why do I can't adress them with index 0-51? 为什么我不能用0-51索引?

Edit: Possible duplicate only explains the shift of 2 indexes, what is the third? 编辑:可能的重复仅说明2个索引的移位,第三个是什么? However: array_values solved the problem. 但是: array_values解决了这个问题。

Use array_values() function to reset the numeric index to start from 0. 使用array_values()函数将数字索引重置为从0开始。

Try: 尝试:

$dirpath = ".....";
$filelist = array_values(preg_grep('~\.(html)$~', scandir($dirpath)));

// print the first value
echo $filelist[0];

Those are the current (.) and parent (..) directories. 这些是当前(。)和父(..)目录。 They are present in all directories, and are used to refer to the directory itself and its direct parent. 它们存在于所有目录中,用于引用目录本身及其直接父目录。
Why is it whenever I use scandir() I receive periods at the beginning of the array? 为什么每当我使用scandir()在数组开头接收到句点时,为什么?

Just use 只需使用

$filelist = array_values($filelist);

Your function is cherry picking the items from an already indexed array, so the keys are not in sequence. 您的功能是从已经索引的数组中挑选项目,因此键不是按顺序排列的。

Using scandir() then applying a regex filter, then re-indexing is an inefficient approach, when glob() can deliver what you want in one call. glob()可以在一个调用中提供所需内容时,使用scandir()然后应用正则表达式过滤器,然后重新索引是一种低效的方法。

The following will generate an array of only .html files. 以下将生成仅.html文件的数组。

If you want to see the dirpath prepended to the filename: 如果要查看文件名前面的目录路径:

$filelist = glob($dirpath . "*.html");  // you may need to add a slash before the filename

If you want to see only the filenames: 如果只想查看文件名:

chdir($dirpath);
$filelist = glob("*.html");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM