PHP:在结果

时间:2015-11-12 10:26:05

标签: php php-5.6

我正在使用scandir和foreach循环向用户显示目录中的文件列表。我的代码如下:

        $dir = scandir('/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files');

        foreach($dir as $directory)
{
        echo "<br/><input type='checkbox' name=\"File[]\" value='$directory'/>$directory<br>";
        }

问题是脚本也回声“。”和一个“..”(没有语音标记),是否有一种优雅的方式来删除这些?短或正则表达式。感谢

3 个答案:

答案 0 :(得分:6)

如果目录为...,则只需continue我建议您查看控制结构here

$dir = scandir('/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files');

foreach($dir as $directory) {
    if( $directory == '.' || $directory == '..' ) {
        // directory is . or ..
        // continue will directly move on with the next value in $directory
        continue;
    }

    echo "<br/><input type='checkbox' name=\"File[]\" value='$directory'/>$directory<br>";
}

而不是:

if( $directory == '.' || $directory == '..' ) {
    // directory is . or ..
    // continue will directly move on with the next value in $directory
    continue;
}

你可以使用它的简短版本:

if( $directory == '.' || $directory == '..' ) continue;

答案 1 :(得分:2)

You can eliminate these directories with array_diff:

$dir = scandir($path);
$dir = array_diff($dir, array('.', '..'));
foreach($dir as $entry) {
    // ...
}

答案 2 :(得分:1)

Another solution, in addition to swidmann's answer, is to simply remove '.' and '..' before iterating over them.

Adapted from http://php.net/manual/en/function.scandir.php#107215

$path    = '/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files';
$exclude = ['.', '..'];
$dir     = array_diff(scandir($path), $exclude);

foreach ($dir as $directory) {
    // ...
}

That way you can also easily add other directories and files to the excluded list should the need arise in the future.