我只是在学习更多关于在PHP中使用类的知识。我知道下面的代码是垃圾,我需要帮助。如果我往正确的方向走,谁能告诉我吗?
while($entryName=readdir($myDirectory)) {
$type = array("index.php", "style.css", "sorttable.js", "host-img");
if($entryName != $type[0]){
if($entryName != $type[1]){
if($entryName != $type[2]){
if($entryName != $type[3]){
$dirArray[]=$entryName;
}
}
}
}
}发布于 2022-07-03 08:55:55
您似乎想要的是目录中没有四个特定名称之一的所有文件的列表。
与您的代码最相似的代码是:
$exclude = array("index.php", "style.css", "sorttable.js", "host-img");
$dirArray = [];
while ($entryName = readdir($myDirectory)) {
if (!in_array($entryName, $exclude)) {
$dirArray[] = $entryName;
}
}或者,您可以省去循环(正如所写的,将在您提供的目录中同时包含文件和目录)。
$exclude = array("index.php", "style.css", "sorttable.js", "host-img");
$contents = scandir($myDirectory);
$dirArray = array_diff($contents, $exclude);编辑以便为后代添加:
@arkascha有一个使用array_filter的答案,虽然这个例子只是array_diff的一个实现,但是这个模式的动机是很好的:有时您可能想排除的不仅仅是一个简单的列表。例如,想象您想要排除特定的文件和所有目录是完全合理的。所以你必须从你的列表中过滤目录。为了好玩,我们也不要返回名字以.开头的任何文件。
$exclude = ["index.php", "style.css", "sorttable.js", "host-img"];
$contents = scandir($myDirectory); // myDirectory is a valid path to the directory
$dirArray = array_filter($contents, function($fileName) use ($myDirectory, $exclude) {
if (!in_array($fileName, $exclude) && strpos('.', $fileName) !== 0) {
return !is_dir($myDirectory.$fileName));
} else {
return false;
}
}发布于 2022-07-03 08:58:30
实际上,您想要过滤输入:
<?php
$input = [".", "..", "folderA", "folderB", "file1", "file2", "file3"];
$blacklist = [".", "..", "folderA", "file1"];
$output = array_filter($input, function($entry) use ($blacklist) {
return !in_array($entry, $blacklist);
});
print_r($output);产出如下:
Array
(
[3] => folderB
[5] => file2
[6] => file3
)这种方法允许实现更复杂的过滤条件,而不必多次传递输入数据。例如,如果您想根据文件扩展名或文件创建时间添加另一个筛选条件,即使是在文件内容上。
https://stackoverflow.com/questions/72844797
复制相似问题