我正在试着把我硬盘上的一些文件夹放入一个数组中。
例如,度假照片。假设我们有这样的结构:
的子集1的
- Subset 2 of Set 2
- Random file, not a dir.
我想要像这样的东西,作为一个数组。
这意味着我有一个很大的数组,并且在这个数组中有更多的数组。每个集合和子集都有自己的数组。
我试着让它看起来像这样:
Array
(
[Set 1] => Array([0] => Item 1 of Set 1, [1] => Item 1 of Set 1,...)
[Set 2] => Array([Subnet 1] => Array([0] => Item 1 of Subset 1 of Set 2,[1] => ...), [Subnet 2] => Array([0] => ..., ..., ...), ..., [0] => Random File)
[set 3] => Array(...)
...
)
我遇到了这个:http://www.the-art-of-web.com/php/dirlist/
但这不是我要找的。我一直在摆弄它,但它只会给我带来麻烦。
这里有一个例子,查看更大分辨率的源代码(显然没有点击...)。
发布于 2009-06-04 18:34:56
我建议使用DirectoryIterator来构建您的阵列
这是我快速拼凑的一个片段,但是我目前还没有一个环境来测试它,所以准备好调试它。
$fileData = fillArrayWithFileNodes( new DirectoryIterator( '/path/to/root/' ) );
function fillArrayWithFileNodes( DirectoryIterator $dir )
{
$data = array();
foreach ( $dir as $node )
{
if ( $node->isDir() && !$node->isDot() )
{
$data[$node->getFilename()] = fillArrayWithFileNodes( new DirectoryIterator( $node->getPathname() ) );
}
else if ( $node->isFile() )
{
$data[] = $node->getFilename();
}
}
return $data;
}
发布于 2009-06-04 18:49:31
一个没有任何错误处理的简单实现:
function dirToArray($dir) {
$contents = array();
# Foreach node in $dir
foreach (scandir($dir) as $node) {
# Skip link to current and parent folder
if ($node == '.') continue;
if ($node == '..') continue;
# Check if it's a node or a folder
if (is_dir($dir . DIRECTORY_SEPARATOR . $node)) {
# Add directory recursively, be sure to pass a valid path
# to the function, not just the folder's name
$contents[$node] = dirToArray($dir . DIRECTORY_SEPARATOR . $node);
} else {
# Add node, the keys will be updated automatically
$contents[] = $node;
}
}
# done
return $contents;
}
发布于 2013-01-22 04:26:10
基于@soulmerge's answer的代码。我刚刚删除了一些nit和注释,并使用$startpath
作为我的起始目录。(谢谢@soulmerge!)
function dirToArray($dir) {
$contents = array();
foreach (scandir($dir) as $node) {
if ($node == '.' || $node == '..') continue;
if (is_dir($dir . '/' . $node)) {
$contents[$node] = dirToArray($dir . '/' . $node);
} else {
$contents[] = $node;
}
}
return $contents;
}
$r = dirToArray($startpath);
print_r($r);
https://stackoverflow.com/questions/952263
复制相似问题