简体   繁体   中英

Make a php json file which display first folder and next files in a directory + how to echo file extension

$dir = "../../";
if(is_dir($dir)){
    if($dh = opendir($dir)){
        while(($file = readdir($dh)) != false){
            if($file != "." and $file != ".."){
                $files_array[] = array('file' => $file);
            } 
        }
    }
    sort($files_array);
    $return_array =array('name_array' => $files_array);
    echo json_encode($return_array);
}

header('Content-type: application/json');

How to make it? There is my source code. I want to know how to sort it + how to echo file extension. Thx:)

  1. header must be set before echo
  2. stop the cycle after recovering the first file, if you only want the first one. Or if you want the first in alphabetical order, return only the first element of the array to return less data. Check if exist first element of array.
  3. set the array empty in case the directory has no files
  4. check that the first result is not a directory, if you want a file

Sample:

    header('Content-type: application/json'); # before echo
    $dir = "../../";
    $files_array=[]; # empty array
    if(is_dir($dir)){
        if($dh = opendir($dir)){
            while(($file = readdir($dh)) != false){
                if($file != "." and $file != ".."){
                    if(!is_dir($file)){ # check is not dir
                        $ext = '';
                        if(strpos($file,'.', 1)) {
                            $aExt = explode(".", $file);
                            # select last element for extension
                            $ext = $aExt[count($aExt)-1];
                        }
                        $files_array[] = array('file' => $file, 'ext'=> $ext ); 
                        break; # break while
                    } 
                } 
            }
        }
        # sort($files_array); # sort multiple file
        # $return_array =array('name_array' => (isset($files_array[0]?$files_array[0]:[]))); # return only first element if exist
        $return_array =array('name_array' => $files_array);
        echo json_encode($return_array);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM