2

我试图弄清楚如何在 CodeIgniter 中使用这个 directory_map 函数。在此处查看手册以获取更多详细信息:http: //codeigniter.com/user_guide/helpers/directory_helper.html

这是我的工作(有点),结果如下:

$this->load->helper('directory');
$map = directory_map('textfiles/');

$index = '';

foreach ($map as $dir => $file) {
  $idx .= "<p> dir: {$dir} </p> <p> file: {$file} </p>";
} #foreach

return $idx;

我的测试环境目录和文件结构:

one [directory]
  subone [sub-directory]
    testsubone.txt [file-in-sub-directory]
  testone.txt [file-in-directory-one]
three [directory]
  testthree.txt [file-in-directory-three]
two [directory]
  testing [sub-directory]
    testagain.txt [file-in-sub-directory-testing]
  test.txt [file-in-directory-testing]
test.txt [file]

这是我认为的输出结果:

dir: 0
dir: two
file: Array
dir: three
file: Array
dir: 1
file: test.txt
dir: one
file: Array

正如您在此结果中看到的那样,并未列出所有目录或文件,有些目录或文件显示为数组。

文件助手中还有一个叫做“get_filenames”的函数。也许它可以以某种方式与 directory_map 一起使用。

另外,我收到以下错误:

A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: welcome.php
Line Number: #

任何帮助将不胜感激。谢谢你=)

4

1 回答 1

2

你的问题是你试图打印出一个多维数组。

您应该尝试这样做:
使用深度计数http://codepad.org/y2qE59XS

$map = directory_map("./textfiles/");

function print_dir($in,$depth)
{
    foreach ($in as $k => $v)
    {
        if (!is_array($v))
            echo "<p>",str_repeat("&nbsp;&nbsp;&nbsp;",$depth)," ",$v," [file]</p>";
        else
            echo "<p>",str_repeat("&nbsp;&nbsp;&nbsp;",$depth)," <b>",$k,"</b> [directory]</p>",print_dir($v,$depth+1);
    }
}

print_dir($map,0);

编辑,另一个没有深度计数的版本: http: //codepad.org/SScJqePV

function print_dir($in)
{
    foreach ($in as $k => $v)
    {
        if (!is_array($v))
            echo "[file]: ",$v,"\n";
        else
            echo "[directory]: ",$k,"\n",print_dir($v);
    }
}

print_dir($map);

请更具体地说明您想要的输出。

编辑评论
这一个保持路径跟踪http://codepad.org/AYDIfLqW

function print_dir($in,$path)
{
    foreach ($in as $k => $v)
    {
        if (!is_array($v))
            echo "[file]: ",$path,$v,"\n";
        else
            echo "[directory]: ",$path,$k,"\n",print_dir($v,$path.$k.DIRECTORY_SEPARATOR);
    }
}

print_dir($map,'');

最后编辑
返回函数http://codepad.org/PEG0yuCr

function print_dir($in,$path)
{
    $buff = '';
    foreach ($in as $k => $v)
    {
        if (!is_array($v))
            $buff .= "[file]: ".$path.$v."\n";
        else
            $buff .= "[directory]: ".$path.$k."\n".print_dir($v,$path.$k.DIRECTORY_SEPARATOR);
    }
    return $buff;
}
于 2012-08-24T09:57:22.017 回答