php - 使用 json 和 php 显示每个文件夹中的文件
问题描述
我有一个使用 PHP 和 JSON 显示文件列表和一些详细信息的 Web 应用程序,我想更改我的代码 si 我可以显示每个文件夹中的所有文件
对于我之前的代码,文件位于文件夹中。所以我想列出/files/folder1、/files/folder2、/files/folder3、...等所有文件
这是我的代码:
<?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
)
);
解决方案
这可能会帮助您:
<?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);
推荐阅读
- powershell - 使用 Get-ADOrganizationalUnit 递归获取 OU?
- python-3.x - 如何使用递归动态添加 n 嵌套 for 循环:
- javascript - 从 localStorage 会话 Javascript 的键中删除一个元素
- vapor - Automatic model migrations in Vapor 4/Fluent still exist?
- java - A problem in eclipse debugger does not work
- javascript - Call vue method from laravel blade
- javascript - Automation: How to get downloaded path of a file that was downloaded from the Web browser
- angular - Apollo Codegen No operations or fragments found to generate code for
- java - Insertion Sort - for loop in Java
- python - Python 3 venv 解释器在 VS Code 中不可用