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

小牛

我想将目录结构转换为带有文件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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章