使用CodeIgniter目录映射帮助程序


Using CodeIgniter Directory Map Helper

我正试图弄清楚如何在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: #

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

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

您应该尝试这样做:
带深度计数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;
}