Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

display files in each folder using json and php

I have a web application that displays a list of files and some details using PHP and JSON, I want to change my code si I can display all files in each folder

For my previous code, the files are in the files folder. So I want to list all files in /files/folder1, /files/folder2, /files/folder3,... and so on

this is my code:

<?php

$dir = "files";

// Run the recursive function    
$response = scan($dir);

// This function scans the files folder recursively, and builds a large array

function scan($dir){
    $files = array();
    // Is there actually such a folder/file?
    if(file_exists($dir)){
        foreach(scandir($dir) as $f) {
            if(!$f || $f[0] == '.') {
                continue; // Ignore hidden files
            }

            if(is_dir($dir . '/' . $f)) {
                // The path is a folder
                $files[] = array(
                    "name" =>$f,
                    "type" => "folder",
                    "path" => $dir . '/' . $f,
                    "items" => scan($dir . '/' . $f) // Recursively get the contents of the folder
                );
            } else {
                // It is a file
                $files[] = array(
                    "name" => $f,
                    "type" => "file",
                    "path" => $dir . '/' . $f,
                    "size" => filesize($dir . '/' . $f) // Gets the size of this file
                );
            }
        }
    }

    return $files;
}

// Output the directory listing as JSON

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

echo json_encode(array(
                    "name" =>; "files",
                    "type" =>; "folder",
                    "path" =>; $dir,
                    "items" =>; $response
                    )
        );

this is how it looks like after applying some style: enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This may help you:

<?php  
$dir = "/var/www/html/cntpanel";    

function scan($dir){ 
   $result = array(); 
   foreach(scandir($dir) as $key => $value){ 
      if(!empty($value) and !in_array($value, array(".", ".."))){ 
         if(is_dir($dir.DIRECTORY_SEPARATOR.$value)){ 
            $result[$value] = scan($dir.DIRECTORY_SEPARATOR.$value); 
         } 
         else{ 
            $result[] = $value; 
         } 
      } 
   }  
   return $result; 
} 

echo json_encode((array)scan($dir), JSON_UNESCAPED_UNICODE);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...