通过平面黑名单数组过滤平面数组
我创建了此代码来循环浏览当前目录中的文件夹并回显该文件夹的链接,一切正常。我将如何使用 $blacklist
数组作为数组来保存我不想要显示的目录的目录名称?
<?php
$blacklist = array('dropdown');
$results = array();
$dir = opendir("./");
while($file = readdir($dir)) {
if($file != "." && $file != "..") {
$results[] = $file;
}
}
closedir($dir);
foreach($results as $file) {
if($blocked != true) {
$fileUrl = $file;
$fileExplodedName = explode("_", $file);
$fileName = "";
$fileNameCount = count($fileExplodedName);
echo "<a href='".$fileUrl."'>";
$i = 1;
foreach($fileExplodedName as $name) {
$fileName .= $name." ";
}
echo trim($fileName);
echo "</a><br/>";
}
}
I've created this code to cycle through the folders in the current directory and echo out a link to the folder, it all works fine. How would I go about using the $blacklist
array as an array to hold the directory names of directories I don't want to show?
<?php
$blacklist = array('dropdown');
$results = array();
$dir = opendir("./");
while($file = readdir($dir)) {
if($file != "." && $file != "..") {
$results[] = $file;
}
}
closedir($dir);
foreach($results as $file) {
if($blocked != true) {
$fileUrl = $file;
$fileExplodedName = explode("_", $file);
$fileName = "";
$fileNameCount = count($fileExplodedName);
echo "<a href='".$fileUrl."'>";
$i = 1;
foreach($fileExplodedName as $name) {
$fileName .= $name." ";
}
echo trim($fileName);
echo "</a><br/>";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
array_diff
是最好的工具这份工作——写起来最短,读起来非常清晰,而且我希望也是最快的。array_diff
is the best tool for this job -- it's the shortest to write, very clear to read, and I would expect also the fastest.为此,请使用 in_array 。
请注意,这是相当昂贵的。 in_array 的运行时复杂度是 O(n),所以不要创建一个大的黑名单。这实际上更快,但代码更“笨拙”:
块检查的运行时复杂度降低到 O(1),因为数组(哈希图)在键查找上的时间是恒定的。
Use in_array for this.
Note that this is rather expensive. The runtime complexity of in_array is O(n) so don't make a large blacklist. This is actually faster, but with more "clumsy" code:
The runtime complexity of the block check is then reduced to O(1) since the array (hashmap) is constant time on key lookup.