我想将目录结构转换为带有文件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
)
)
)
任何人都可以帮我实现这个目标吗? 非常感谢提前。
答案 0 :(得分:4)
应该更容易。 通常,如果您有递归,则不需要状态。 因此,只需阅读您的$ 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;
}