[英]PHP case switch behaviour breaks a recursive scandir function
在我尋求一些基本的PHP知識時,我試圖做一個簡單的函數來讀取不會使用遞歸迭代器的文件和目錄。 (更多的練習但實際上需要任何php <5.3服務器)
該功能運行良好 - 但當我嘗試添加一個switch
($輸出) - 它不再列出所有文件(例如,在添加開關之前,它可以看到4個文件夾中的61個文件(3 +根)但是添加switch
它只能看到47(只有root)。我在這里做錯了嗎?為什么switch
語句打破了虛假的“recursive-nest”?
function o99_list_my_files_scandir($dir,$output)
{
$result = $result2 = array();
$root = scandir($dir);
foreach($root as $value)
{
if($value === '.' || $value === '..' || $value == 'Thumb.db' || $value == 'Thumbs.db' || $value == '') { continue;}
if(is_file("$dir/$value")) {$result[]="$dir/$value"; continue;} // array files
if(is_dir("$dir/$value")) {$result2[]="$dir/$value"; continue;} // array dirs
foreach(o99_list_my_files_scandir("$dir/$value") as $value)
{
$result[] = $value;
}
}
// this is the troublemaker ...
switch ($output) {
case 'dirs' :
return array_filter($result2); // clean empty results of dirs
break;
case 'files' :
return array_filter($result); // Clean empty array of files
break;
}
}
有沒有其他簡單的方法來讓函數返回dirs AND文件的單獨列表而不是統一的數組?
因為在這一行......
foreach(o99_list_my_files_scandir("$dir/$value") as $value)
...你沒有給遞歸調用函數的$output
,所以它不會輸出任何東西。 將其更改為:
foreach(o99_list_my_files_scandir("$dir/$value", $output) as $value)
實際上你應該對失蹤的論點發出警告。
你似乎沒有在任何地方設置$output
。
順便說一句:出於學習目的,我強烈建議添加error_reporting(E_ALL);
作為腳本的第一行並重新運行(首先,不修復任何內容),因為您應該看到警告,因為第二個函數參數不是可選的。 你有簽名
function o99_list_my_files_scandir($dir,$output)
但是打電話
o99_list_my_files_scandir("$dir/$value")
而你應該
o99_list_my_files_scandir("$dir/$value", $output)
在你的foreach()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.