我想在 php 中創建一個檔案夾樹陣列。我編碼了一些東西,它快完成了,但是有一些問題。
因此,所有檔案和檔案夾都應位于與檔案夾中相同的 json 中。這是我的代碼:
function getDirContents($dir, &$results = array(), $counter = 0 ) {
$files = scandir($dir);
foreach ($files as $key => $value) {
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
if (!is_dir($path)) {
$results[] = array('name'=>$path,'type'=>'file');
} else if ($value != "." && $value != "..") {
$results[] = array('name'=>$path,'type'=>'folder','subfolders'=>array());
getDirContents($path, $results[count($results)]['subfolders']);
}
}
return $results;
}
print_r(json_encode(getDirContents('./')));
結果如下。但它在不同的地方有子檔案夾標簽。例如; 子檔案夾 test4 應該在 test2 子檔案夾中,但它是 test2 檔案夾中的區域。
[
{
"name":"C:\\xampp\\htdocs\\test\\test.php",
"type":"file"
},
{
"name":"C:\\xampp\\htdocs\\test\\test.txt",
"type":"file"
},
{
"name":"C:\\xampp\\htdocs\\test\\test1",
"type":"folder",
"subfolders":[
]
},
{
"subfolders":[
{
"name":"C:\\xampp\\htdocs\\test\\test1\\test2",
"type":"folder",
"subfolders":[
]
},
{
"subfolders":[
{
"name":"C:\\xampp\\htdocs\\test\\test1\\test2\\test4",
"type":"folder",
"subfolders":[
]
},
{
"subfolders":null
}
]
},
{
"name":"C:\\xampp\\htdocs\\test\\test1\\test3.txt",
"type":"file"
}
]
},
{
"name":"C:\\xampp\\htdocs\\test\\test_1.php",
"type":"file"
}
]
結果應該是這樣的:
[
{
"folder1": {
"name": "test1.txt",
"type": "file",
"subfolders": {
"subfolder1": {
"name": "test1",
"type": "folder"
},
"subfolder2": {
"name": "test2",
"type": "folder",
"subfolders": {
"subfolder3": {
"name": "test3",
"type": "folder"
},
"subfile":{
"name":"test3.txt"
"type":"file"
}
}
}
}
}
}
]
我希望我能解釋一下我的情況。結果,datas 不在一個back datas 中。
uj5u.com熱心網友回復:
問題就在這里,當您getDirContents($path, $results[count($results)]['subfolders']);遞回呼叫時,您提供了帶有錯誤陣列索引的第二個引數。當您將第一個檔案夾存盤到$results它時,它的索引在陣列 = 0 中。但是隨后您使用count()函式從$results陣列中獲取記錄數,它回傳1not 0。此外,我認為您已禁用通知錯誤報告,而您只是沒有看到它。用array_key_last或替換 count($results)count($results) - 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/344894.html
