scandir to only show folders, not files

后端 未结 4 1992
一整个雨季
一整个雨季 2021-01-01 22:49

I have a bit of PHP used to pulled a list of files from my image directory - it\'s used in a form to select where an uploaded image will be saved. Below is the code:

相关标签:
4条回答
  • 2021-01-01 23:25

    You could just use your array_map function combined with glob

    $folders = array_map(function($dir) {
        return basename($dir);
    }, glob('../images/*', GLOB_ONLYDIR));
    

    Yes, I copied a part of it of dev-null-dweller, but I find my solution a bit more re-useable.

    0 讨论(0)
  • 2021-01-01 23:29

    The easiest and quickest will be glob with GLOB_ONLYDIR flag:

    foreach(glob('../images/*', GLOB_ONLYDIR) as $dir) {
        $dirname = basename($dir);
    }
    
    0 讨论(0)
  • 2021-01-01 23:35

    The is_dir() function requires an absolute path to the item that it is checking.

    $base_dir    = get_home_path() . '/downloads'; 
    //get_home_path() is a wordpress function
    $sub_dirs = array();
    $dir_to_check = scandir($dir);
    foreach ($dir_to_check as $item){
      if ($item != '..' && $item != '.' && is_dir($base_dir . "/" . $item)){
        array_push($sub_dirs, $item);
      }
    }
    
    0 讨论(0)
  • 2021-01-01 23:37

    Function is_dir() is the solution :

    foreach ($files as $file) {
    
      if(is_dir($file) and $file != "." && $file != "..") $filelist .= sprintf('<option value="%s">%s</option>' . PHP_EOL, $file, $file );
    
    }
    
    0 讨论(0)
提交回复
热议问题