Deep recursive array of directory structure in PHP

后端 未结 5 2260
有刺的猬
有刺的猬 2020-11-27 18:22

I\'m trying to put some folders on my hard-drive into an array.

For instance, vacation pictures. Let\'s say we have this structure:

  • Set 1
    • Ite
5条回答
  •  孤城傲影
    2020-11-27 19:22

    A simple implementation without any error handling:

    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;
    }
    

提交回复
热议问题