如何在 PHP 中将目录树保存到数组中?

发布于 2024-10-08 06:11:45 字数 870 浏览 0 评论 0原文

我正在尝试获取具有以下结构的目录:

top
    folder1
        file1
    folder2
        file1
        file2

并将其保存到数组中,例如:

array
(
    'folder1' => array('file1'),
    'folder2' => array('file1', 'file2')
)

这样,我可以轻松地在整个站点中重复使用该树。我一直在研究这段代码,但它仍然没有达到我想要的效果:

private function get_tree()
{
    $uploads  = __RELPATH__ . DS . 'public' . DS . 'uploads';
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads), RecursiveIteratorIterator::SELF_FIRST);
    $output   = array();

    foreach($iterator as $file)
    {
        $relativePath = str_replace($uploads . DS, '', $file);

        if ($file->isDir())
        {
            if (!in_array($relativePath, $output))
                $output[$relativePath] = array();
        }
    }

    return $output;
}

I'm trying to take a directory with the structure:

top
    folder1
        file1
    folder2
        file1
        file2

And save it into an array like:

array
(
    'folder1' => array('file1'),
    'folder2' => array('file1', 'file2')
)

This way, I can easily resuse the tree throughout my site. I've been playing around with this code but it's still not doing what I want:

private function get_tree()
{
    $uploads  = __RELPATH__ . DS . 'public' . DS . 'uploads';
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads), RecursiveIteratorIterator::SELF_FIRST);
    $output   = array();

    foreach($iterator as $file)
    {
        $relativePath = str_replace($uploads . DS, '', $file);

        if ($file->isDir())
        {
            if (!in_array($relativePath, $output))
                $output[$relativePath] = array();
        }
    }

    return $output;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绝不服输 2024-10-15 06:11:45

我对递归函数感到恐惧。但我设法想出了这个..不确定这就是你要找的

function tree($path, $top) {
    $ignore = array('cgi-bin', '.', '..' ); 
    $handle = opendir($path);   

    while( ($file = readdir($handle)) !== false ) {

        if( !in_array( $file, $ignore ) ){              
            if( is_dir("$path/$file") ) {
                $top[$file] = @ tree("$path/$file", $top[$file]);
            } else {
                $top[] = $file;
            }
        }

    }

    closedir( $handle );
    return $top;
}

假设你的目录树是

alt text

它输出

Array
(
    [a] => Array
        (
            [aa] => Array
                (
                    [0] => aa.txt
                )

        )

    [b] => Array
        (
            [0] => bb.txt
        )

    [c] => Array
        (
            [0] => cc.txt
        )

)

但是,休息一下,去观看每 300 年或几年一次的日食​​。当你的孩子、孙子、曾孙问你“你知道冬至日食发生时你还活着吗?”时,你不想说“不”。你看到了吗????”

:)

Im horrible with recursive functions. But i managed to come up with this..not sure it's what you're looking for

function tree($path, $top) {
    $ignore = array('cgi-bin', '.', '..' ); 
    $handle = opendir($path);   

    while( ($file = readdir($handle)) !== false ) {

        if( !in_array( $file, $ignore ) ){              
            if( is_dir("$path/$file") ) {
                $top[$file] = @ tree("$path/$file", $top[$file]);
            } else {
                $top[] = $file;
            }
        }

    }

    closedir( $handle );
    return $top;
}

Assuming your directory tree is

alt text

it outputs

Array
(
    [a] => Array
        (
            [aa] => Array
                (
                    [0] => aa.txt
                )

        )

    [b] => Array
        (
            [0] => bb.txt
        )

    [c] => Array
        (
            [0] => cc.txt
        )

)

But, take a break and go watch the eclipse that happens every 300 and something years. You dont want to say 'no' when your kids, grandkids, great-grandkids ask you 'did you know you were alive when the winter solstice eclipse occurred?? did you see it?????"

:)

懵少女 2024-10-15 06:11:45

您似乎没有解决 $relativePath 不是目录的情况。您没有描述您的输出,但我认为它完全由空数组组成,而内部没有所需的文件。这是正确的吗?

您需要处理到达文件而不是目录的最终情况。你自己尝试一下,如果你仍然在挣扎,我可以稍后尝试为你发帖。

而且,恐怕这无法处理更深的问题。虽然我不确定你是否需要根据你的例子。

--编辑--

正如我在下面解释的那样,这不会构建完整的树,但根据您要查找的内容可能没问题。一棵完整的树需要一些更重大的改变。但是,我下面发布的内容至少应该将文件放入文件夹中。

private function get_tree()
{
    $uploads  = __RELPATH__ . DS . 'public' . DS . 'uploads';
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads), RecursiveIteratorIterator::SELF_FIRST);
    $output   = array();

    foreach($iterator as $file)
    {
        $relativePath = str_replace($uploads . DS, '', $file);

        if ($file->isDir())
        {
            if (!in_array($relativePath, $output))
            {
                $output[$relativePath] = array();
                $lastDir = $relativePath;
            }
        }
        else 
        {
             $p = path_info($file);
             $d = $p['dirname']; $f = $p['basename'];
             $output[$d][] = basename($f); 
        }
    }

    return $output;
}

It appears you didn't address the case in which $relativePath is not a directory. You did not describe your output, but i suppose it consists entirely of empty arrays without the desired files ever being inside. Is this correct?

You need to handle the end-case where a file is reached instead of a directory. Take a stab yourself, I can try to post for you later if you are still struggling.

Also, I'm afraid this won't deal with greater depths. Although I am not sure if you need that based on your example.

--EDIT--

This won't build a full tree, as i explained the comment below, but depending on what you're looking for that might be ok. A full tree would take some more significant changes. However, what I post below should at least put the files into the folders.

private function get_tree()
{
    $uploads  = __RELPATH__ . DS . 'public' . DS . 'uploads';
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads), RecursiveIteratorIterator::SELF_FIRST);
    $output   = array();

    foreach($iterator as $file)
    {
        $relativePath = str_replace($uploads . DS, '', $file);

        if ($file->isDir())
        {
            if (!in_array($relativePath, $output))
            {
                $output[$relativePath] = array();
                $lastDir = $relativePath;
            }
        }
        else 
        {
             $p = path_info($file);
             $d = $p['dirname']; $f = $p['basename'];
             $output[$d][] = basename($f); 
        }
    }

    return $output;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文