如何将目录结构转换为 url 数组

How to convert directory structure to array of urls

我想将我的目录结构转换为带有文件 URL 的数组格式。 这是我的目录结构。

public
  |-product_001
      |-documents
      |   |- doc_001.txt
      |   |- doc_002.txt
      |   |- doc_003.txt
      |
      |-gallery
          |- img_001.png
          |- img_002.png
          |- img_003.png

这就是我想要的:

array(
  'product_001' =>array(
      'documents' =>array(
         0 => "public/product_001/documents/doc_001.txt",
         1 => "public/product_001/documents/doc_002.txt",
         2 => "public/product_001/documents/doc_003.txt"
      )
      'gallery' =>array(
         0 => "public/product_001/gallery/img_001.png",
         1 => "public/product_001/gallery/img_002.png",
         2 => "public/product_001/gallery/img_003.png"
      )
  )
)

函数如下:

function dirToArray($dir,$url) {

    $result = array();

    $cdir = scandir($dir);
    foreach ($cdir as $key => $value) {

        if (!in_array($value, array(".", ".."))) {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
                $url.=DIRECTORY_SEPARATOR.$value;
                $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value,$url);
            } else {
                $result[] = $url.DIRECTORY_SEPARATOR.$value;
            }
        }
    }

    return $result;
}

这是我到目前为止得到的输出:

Array
(
    [product_001] => Array
        (
            [documents] => Array
                (
                    [0] => public/product_001/documents/doc_001.txt
                    [1] => public/product_001/documents/doc_002.txt
                    [2] => public/product_001/documents/doc_003.txt
                )

            [gallery] => Array
                (
               [0] => public/product_001/documents/gallery/img_001.png
               [1] => public/product_001/documents/gallery/img_002.png
               [2] => public/product_001/documents/gallery/img_003.png
                )

        )

)

谁能帮我实现这个目标? 非常感谢。

应该更容易。 通常,如果您有递归,则不需要状态。 因此,只需阅读您的 $url 并清理代码,无需多次进行连接。

根据 Ryan Vincents' 评论添加了动态分隔符。

根据 Mavericks' 注释添加根参数。

<?php

function dirToArray($dir, $separator = DIRECTORY_SEPARATOR, $root = '') {

    $result = array();
    if ($root === '') {
        $root = $dir;
    }

    $cdir = scandir($dir);
    foreach ($cdir as $key => $value) {

        if (!in_array($value, array(".", ".."))) {
            $current = $dir . $separator . $value;

            if (is_dir($current)) {
                $result[$value] = dirToArray($current, $separator, $root);
            } else {
                $result[] = str_replace($root, '',$current);
            }
        }
    }

    return $result;
}