【问题标题】:Scandir: Checking for files with the same name (excluding extension)Scandir:检查同名文件(不包括扩展名)
【发布时间】:2013-02-28 22:46:28
【问题描述】:

是否可以检查具有相同文件名的文件(仅文件扩展名不同)并且只显示它们的名称一次?

if (is_dir($dir_path)) {

    $files = scandir($dir_path);

    foreach($files as $file) {

        if ( !in_array( $file, $exclude_all ) ) {

            $path_to_file = $dir_path . $file;
            $bare_name = pathinfo( $path_to_file, PATHINFO_FILENAME );
            $extension = pathinfo( $path_to_file, PATHINFO_EXTENSION );

            echo 'Path to file: ' . $path_to_file . '<br />';
            echo 'Bare file name: ' . $bare_name . '<br />';
            echo 'Extension: ' . $extension . '<br />';         

        }
    }
}

【问题讨论】:

  • 你能告诉我吗? ;)

标签: php scandir


【解决方案1】:
you can try this:

//first save all files in an array
$bare_name = pathinfo( $path_to_file, PATHINFO_FILENAME );
if(!in_array($bare_name, $files)){
 $files[] = $bare_name;
}

现在 $files 包含唯一的文件名

【讨论】:

    【解决方案2】:

    试试这个

    if (is_dir($dir_path)) {
    
    $tmpBareNames = array();
    
    $files = scandir($dir_path);
    
    foreach($files as $file) {
    
        if ( !in_array( $file, $exclude_all ) ) {
    
            $path_to_file = $dir_path . $file;
            $bare_name = pathinfo( $path_to_file, PATHINFO_FILENAME );
            if(!in_array($bare_name,$tmpBareNames))
                $tmpBareName[] = $bare_name;
            else break;
            $extension = pathinfo( $path_to_file, PATHINFO_EXTENSION );
    
            echo 'Path to file: ' . $path_to_file . '<br />';
            echo 'Bare file name: ' . $bare_name . '<br />';
            echo 'Extension: ' . $extension . '<br />';         
    
        }
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多