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']); 时,问题就出在这里,您为第二个参数提供了错误的数组索引。当您将第一个文件夹存储到 $results 时,它在数组中的索引 = 0。但是随后您使用 count() 函数从 $results 数组中获取记录数 returns 1 不是 0。此外,我认为您已禁用通知错误报告,而您只是没有看到它。 将 count($results) 替换为 array_key_lastcount($results) - 1