簡體   English   中英

PHP中的遞歸文件夾樹

[英]Recursive folder tree in PHP

我想在 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 中。

當您調用getDirContents($path, $results[count($results)]['subfolders']);時,問題就在這里getDirContents($path, $results[count($results)]['subfolders']); 遞歸地,您提供具有錯誤數組索引的第二個參數。 當您將第一個文件夾存儲到$results它在 array = 0 中有索引。但是隨后您使用count()函數從$results數組中獲取記錄數,它返回1而不是0 此外,我認為您已禁用通知錯誤報告,而您只是沒有看到它。 array_key_lastcount($results) - 1替換 count($results)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM