Problems with continue in foreach loop

时间:2015-09-14 15:34:00

标签: php

This is my code:

<?php
function recursive($directory){
    $nr = 0;
    $files = scandir($directory);
    foreach($files as $file){
        if($file == '.' || $file == '..') continue;
        if(is_dir($file)){
            echo $file.'<br>';
            continue;
        }
        echo $file.' ----------<br>';

    }
}
recursive('.');
?>

Basically I want the code at the bottom of the loop to be skipped until they are no more files in the directory.

How I want it to look:

enter image description here

How it looks:

enter image description here

3 个答案:

答案 0 :(得分:2)

A different take on your code but have you looked at the recursiveIterator family of classes? It's part of the php core and is pretty powerful.

        $folder='c:/temp';
        foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $folder, RecursiveDirectoryIterator::KEY_AS_PATHNAME ), RecursiveIteratorIterator::CHILD_FIRST ) as $file => $info ) {
            if( $info->isFile() && $info->isReadable() && $info->isWritable() ){
                echo $info->getFilename().'-------<br />';
            } elseif( $info->isDir() ){
                echo $info->getPath().'<br />';
            }
        }

答案 1 :(得分:1)

I think you first need to list the directories, then the files. You can do that by changing a bit your function and running it twice:

function recursive($directory, $type){
    $nr = 0;
    $files = scandir($directory);
    foreach($files as $file){
        if($file == '.' || $file == '..') continue;
        if(is_dir($file) && $type == 'dir'){
            echo $file.'<br>';
        } else if(!is_dir($file) && $type == 'file'){
            echo $file.' ----------<br>';
        }
    }
}
recursive('.', 'dir');
recursive('.', 'file');

(By the way, although it's called "recursive", it doesn't do recursion)

答案 2 :(得分:0)

Like this?

echo $file.'<br>';
if(is_dir($file) === false){
    echo $file.' ----------<br>';            
}
相关问题