[英]How to build an indexed array of .html filenames that exist in a directory?
我正在使用此php代碼來獲取給定目錄中的所有html文件:
$dirpath = ".....";
$filelist = preg_grep('~\.(html)$~', scandir($dirpath));
現在,我想獲取數組中的特定元素,例如:
echo $filelist[0];
這失敗了。 在我的目錄中有52個文件, count($filelist)
返回'52',但是要獲取第一個元素,我需要使用echo $filelist[3];
最后一項通過索引54獲取地址。這是什么? 為什么我不能用0-51索引?
編輯:可能的重復僅說明2個索引的移位,第三個是什么? 但是: array_values
解決了這個問題。
使用array_values()
函數將數字索引重置為從0開始。
嘗試:
$dirpath = ".....";
$filelist = array_values(preg_grep('~\.(html)$~', scandir($dirpath)));
// print the first value
echo $filelist[0];
這些是當前(。)和父(..)目錄。 它們存在於所有目錄中,用於引用目錄本身及其直接父目錄。
為什么每當我使用scandir()在數組開頭接收到句點時,為什么?
只需使用
$filelist = array_values($filelist);
您的功能是從已經索引的數組中挑選項目,因此鍵不是按順序排列的。
當glob()
可以在一個調用中提供所需內容時,使用scandir()
然后應用正則表達式過濾器,然后重新索引是一種低效的方法。
以下將生成僅.html文件的數組。
如果要查看文件名前面的目錄路徑:
$filelist = glob($dirpath . "*.html"); // you may need to add a slash before the filename
如果只想查看文件名:
chdir($dirpath);
$filelist = glob("*.html");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.