文件路径转换为数组php,php – 如何将目录结构转换为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

)

=> 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的评论添加了根参数.

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;

}

标签:php,arrays,directory-structure

来源: https://codeday.me/bug/20190623/1271009.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值