php - 需要帮助格式化 PHP、javascript 树控件中目录列表的结果

标签 php javascript jquery html

我正在尝试使用 PHP 列出一个特定文件夹内的所有文件夹和文件。使用下面的代码,我成功地在一个长列表中列出了所有文件和文件夹。现在我真正想做的是列出它们,以便我可以使用 HTML/jquery 将目录结果显示为旁边带有 + 标记的文件夹,以便可以扩展它们,但我不知道如何格式化结果PHP 才能做到这一点。

 include('include/class.dirlist.php');
 $resources = "/Inetpub/companyweb/resources";
 $dir = getDirectoryListing($resources,"a",1,1,"all",1);

 $i = 0; //for illustrative purposes only 
 foreach ($dir as $item) {
     echo "<b><a href='resources/".$dir[$i]."'>".$dir[$i]."</a></b><br>";
     $i++;
 }

上面的代码将输出如下内容:

文件夹1
文件夹1/文件1.PDF
文件夹1/文件2.PDF
文件夹2
文件夹2/文件1.PDF
文件夹2/文件2.PDF

以下是我对以下评论的回复: @hek2mgl 这正是我想做的。我想要一个树型 View 。

@popnoodles 如果我能把它变成“ul li”格式,我相信我可以使用它。问题是,我是一名 PHP 初学者...所以在这里寻找一个可行的解决方案。

@Bjørne Malmanger 以下是包含的类的内容:

function getDirectoryListing($dirname, $sortorder = "a", $show_subdirs = 1,         $show_subdirfiles = 0, $exts = "all", $ext_save = 1) {
// This function will return an array with filenames based on the criteria you can set in the variables
// @sortorder : a for ascending (the standard) or d for descending (you can use the "r" for reverse as well, works the same)
// @show_subdirs : 0 for NO, 1 for YES - meaning it will show the names of subdirectories if there are any
// Logically subdirnames will not be checked for the required extentions
// @show_subdirfiles : 0 for NO, 1 for YES - meaning it will show files from the subdirs
// Files from subdirs will be prefixed with the subdir name and checked for the required extentions.
// @exts can be either a string or an array, if not passed to the function, then the default will be a check for common image files
// If exts is set to "all" then all extentions are allowed
// @ext_save : 1 for YES, 0 for NO - meaning it will filter out system files or not (such as .htaccess)

if (!$exts || empty($exts) || $exts == "") {
   $exts = array("jpg", "gif", "jpeg", "png", "doc", "xls", "pdf", "tif");
}
if ($handle = opendir($dirname)) {
   $filelist = array();
   while (false !== ($file = readdir($handle))) {

       // Filter out higher directory references
       if ($file != "." && $file != "..") {
           // Only look at directories or files, filter out symbolic links
           if ( filetype ($dirname."/".$file) != "link") {
               // If it's a file, check against valid extentions and add to the list
               if ( filetype ($dirname."/".$file) == "file" ) {
                   if (checkFileExtention($file, $exts, $ext_save)) {
                                   $filelist[] = $file;
                   }
               }
               // If it's a directory and either subdirs should be listed or files from subdirs add relevant names to the list
               else if ( filetype ($dirname."/".$file) == "dir" && ($show_subdirs == 1 || $show_subdirfiles == 1)) {
                   if ($show_subdirs == 1) {
                       $filelist[] = $file;
                   }
                   if ($show_subdirfiles == 1) {
                       $subdirname = $file;
                       $subdirfilelist = getDirectoryListing($dirname."/".$subdirname."/", $sortorder, $show_subdirs, $show_subdirfiles, $exts, $ext_save);
                       for ($i = 0 ; $i < count($subdirfilelist) ; $i++) {
                           $subdirfilelist[$i] = $subdirname."/".$subdirfilelist[$i];
                       }
                       $filelist = array_merge($filelist, $subdirfilelist);
                   }

               }

           }
       }
   }
   closedir($handle);

   // Sort the results
   if (count($filelist) > 1) {
       natcasesort($filelist);
       if ($sortorder == "d" || $sortorder == "r" ) {
           $filelist = array_reverse($filelist, TRUE);
       }
   }
   return $filelist;
  }
  else {
    return false;
 }
 }

 function checkFileExtention($filename, $exts, $ext_save = 1) {
 $passed = FALSE;
 if ($ext_save == 1) {
   if (preg_match("/^\./", $filename)) {
       return $passed;
   }
 }
 if ($exts == "all") {
               $passed = TRUE;
   return $passed;
 }
 if (is_string($exts)) {
   if (eregi("\.". $exts ."$", $filename)) {
                   $passed = TRUE;
       return $passed;
   }
  } else if (is_array($exts)) {
   foreach ($exts as $theExt) {
       if (eregi("\.". $theExt ."$", $filename)) {
           $passed = TRUE;
           return $passed;
        }
    }
  }
  return $passed;
  }

最佳答案

看看jstree 。我想这就是你想要的。 (我是使用 jstree 完成的)。 Jstree 是一个 javascript 库,可用于控制渲染树结构,如 HTML 列表 ( <ul>, <ol> ) 或 json 或 xml 作为可控树,并使用“+”来打开和关闭您希望的文件夹。

当然jstree只是javascript部分。您必须格式化 getDirectoryListing() 的输出为 jstree 支持的格式之一。目前这是

  • Json
  • XML
  • HTML

这是一个基本示例。完成后,它将如下所示:

finished example in browser

您可以尝试打开和关闭树节点。

我已将您的目录列表函数更改为为 jstree 生成 JSON 的函数。它实际上源自这个SO post让事情快速运转。谢谢! :) 这是 php.ini。将其放在网络服务器中的文件夹中并将其命名为 tree.php

<?php

header('Content-Type: application/json');
echo json_encode(dir_to_jstree_array(__DIR__));

function dir_to_jstree_array($dir, $order = "a", $ext = array()) {

    if(empty($ext)) {
        $ext = array (
            "jpg", "gif", "jpeg", "png", "doc", "xls", "pdf", "tif"
        );
    }

    $listDir = array(
        'data' => basename($dir),
        'attr' => array (
            'rel' => 'folder'
        ),
        'metadata' => array (
            'id' => $dir
        ),
        'children' => array()
    );

    $files = array();
    $dirs = array();

    if($handler = opendir($dir))
    {
        while (($sub = readdir($handler)) !== FALSE)
        {
            if ($sub != "." && $sub != "..")
            {
                if(is_file($dir."/".$sub))
                {
                    $extension = pathinfo($dir."/".$sub, PATHINFO_EXTENSION);
                    if(in_array($extension, $ext)) {
                        $files []= $sub;
                    }
                }elseif(is_dir($dir."/".$sub))
                {
                    $dirs []= $dir."/".$sub;
                }
            }
        }

        if($order === "a") {
            asort($dirs);
        } else {
            arsort($dirs);
        }

        foreach($dirs as $d) {
            $listDir['children'][]= dir_to_jstree_array($d);
        }

        if($order === "a") {
            asort($files);
        } else {
            arsort($files);
        }

        foreach($files as $file) {
            $listDir['children'][]= $file;
        }

        closedir($handler);
    }
    return $listDir;
}

这里是基本的 HTML 和 javascript。给它一个合适的名称并将其放在 tree.php 旁边。我将 jstree 的 json_data 插件与 ajax 一起使用。此外,我还使用 types 插件来呈现文件夹和文件的不同类型的图标。 (如果您愿意,也可以为每种文件类型提供自定义图标)。您必须在 html 文件旁边放置适当的folder.png 和image.png。

<html>
  <head>
    <script type="text/javascript" src="jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="jstree-v.pre1.0/jquery.jstree.js"></script>
    <script type="text/javascript">

        $(function() {
          $('#dirtree').jstree({
            plugins : ["json_data", "themes", "types"],

            json_data : {
              ajax : {
                'url' : 'tree.php'
              }
            },

            'types': {
              'types' : {

                'folder' : {
                  'icon' : {
                    'image' : 'folder.png'
                  }
                },

                'default' : {
                  'icon' : {
                    'image' : 'image.png'
                  },
                }
              }
            }
          });
        }); 

    </script>
 </head>
 <body>
   <div id="dirtree"></div>
 </body>
</html>

就是这样! :) 请注意,jstree 有许多配置选项、样式选项和插件。您当然会扩展我的示例。

请参阅上面的 jstree 项目页面链接,了解有关 jstree 安装和文档的信息。

关于php - 需要帮助格式化 PHP、javascript 树控件中目录列表的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14389757/

相关文章:

php - Mysql统计6列之间的数字组合

javascript - 如何确保我的值已添加并存在,然后运行另一个代码 jquery?

jquery - 溢出 :auto in jqgrid not working after upgrading jquery from 1. 6.2 到 3.2.1

php - 可滚动表格上方的固定标题

php 日期格式帮助 日期格式不提供有效日期,即使它与文档匹配

PHP:修剪对象中的每个元素,如果为空,则设置为 N/A

javascript - 根据 Javascript 中的名称生成颜色

javascript - 现有功能的 Keydown 和 Keyup

javascript - 如何在 NodeJS 中混合音频文件

javascript - 弹出窗口打开后立即变灰并禁用父窗口