dongmu9253 2011-05-07 10:34
浏览 20
已采纳

PHP阵列阻止列表

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 dont want to show?

$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/>";
    }
}
  • 写回答

2条回答 默认 最新

  • douli4852 2011-05-07 10:37
    关注

    Use in_array for this.

    $blocked = in_array($file, $blacklist);
    

    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:

    $blacklist = array('dropdown' => true);
    /* ... */
    $blocked = isset($blacklist[$file]);
    

    The runtime complexity of the block check is then reduced to O(1) since the array (hashmap) is constant time on key lookup.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于Simulink的ZPW2000轨道电路仿真
  • ¥15 pycharm找不到在环境装好的opencv-python
  • ¥15 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题