duanran3115 2015-04-10 09:13
浏览 26

需要在目录-php中显示有限数量的文件名

For the below code I have multiple directories and files. I can display one filename per directory(Which is good with the "BREAK").

<?php
    $dir = "/images/";
    $i=0;
    // Open a directory, and read its contents
    if (is_dir($dir)){
        if ($dh = opendir($dir)){
            while (($file = readdir($dh)) !== false){
                echo "filename:" . $file . "<br>";
                break;
                //---- if ($i>=5) { break; }
            }
            closedir($dh);
        }
    }
?>

With if ($i>=5) { break; } I can still display 5 filenames but it reads only one directory.

I want to display at least 5 file names from all directories, how can I do it?

  • 写回答

3条回答 默认 最新

  • dongmou9260 2015-04-10 09:22
    关注

    You don't have to break it, you can just skip it. And in doing so, you have to use continue instead.

    $dir = "/images/";
    $i=0;
    
    // Open a directory, and read its contents
    if (is_dir($dir)){
        if ($dh = opendir($dir)){
            while (($file = readdir($dh)) !== false){
                echo "filename:" . $file . "<br>";
    
                if ($i>=5)
                       continue;
    
            }
            closedir($dh);
        }
    }
    

    Here is also another scenario. Because you mentioned that you have many directories but you only show one main directory, I am guessing that the directories you've mentioned were inside the /images/ directory.

    $dir = "images/";
    $i=1;
    
    // Open a directory, and read its contents
    if (is_dir($dir)){
        if ($dh = opendir($dir)){
            while (($file = readdir($dh)) !== false){
    
                $j=1;
    
                if (is_dir($file)) {
                    if ($internalDir = opendir($file)) {
                        while (($internalFile = readdir($internalDir)) !== false) {
                            echo $file."->filename: ".$internalFile."<br>";
    
                            if ($j>=5)
                                   continue;
    
                            $j++;
                        }
    
                        closedir(opendir($file));
                    }
    
                } else {
                    echo "filename:" . $file . "<br>";
    
                    if ($i>=5)
                       continue;
    
                    $i++;
                }
    
    
            }
            closedir($dh);
        }
    }
    

    Read more about continue here: http://php.net/manual/en/control-structures.continue.php

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭