如何在树枝中显示数组的内容


How to display contents of array in twig

我花了 3 天时间寻找解决方案:/

我有一个循环遍历目录内容的函数:

我正在把一些东西放在一起,但它有很多 for 循环,所以我在网上搜索并找到了类似的东西,我可以修改以适应我需要的东西:

   require_once "library/Twig/Autoloader.php";
  Twig_Autoloader::register();
  $loader = new Twig_Loader_Filesystem('views/');
  $twig = new Twig_Environment($loader);
$dir = dirname(dirname(__FILE__)) . '/';
  function fileList($dir){
     global $files;
     $files = scandir($dir);
      foreach($files as $file){
          if($file != '.' && $file != '..'){
              if(is_dir($dir . $file)){
                 fileList($dir . $file);
               }
          }
      }
  };
  fileList($dir);

然后我有这个:

  echo $twig->render('home.twig', array('file' => $files, 'dir' => $dir));

在我的 home.twig 文件中,我有这个:

      <ol>
        {% for key, files in file %}
           <li>{{file[key]}}</li>
        {% endfor %}
      </ol>

我想做的是使用页面上的树枝在$files上显示内容,但我无法绕开它。 请帮忙?

这很奇怪,我注意到当我在函数中添加global $files;时,它只输出第一个目录的内容并停止。 不知道为什么会停止。

下面是该函数的稍微重新设计的版本,它将递归到子文件夹中,并在单个平面数组中列出所有内容:

function fileList($dir, &$files = array()){
    $this_dir = scandir($dir);
    foreach($this_dir as $file){
        if($file != '.' && $file != '..'){
            if(is_dir($dir . $file)){
                fileList($dir.$file.'/', $files);
            } else {
                $files[] = $dir . $file;
            }
        }
    }
}

下面是函数用法的简短示例:

$dir = dirname(dirname(__FILE__)) . '/';
fileList($dir, $files);
echo '<h2>Scanning Directory: '.$dir.'</h2>'; //These two lines are
echo '<pre>'.print_r($files, true).'</pre>'; //just to see the results

然后在树枝输出中,您只需要一个简单的循环即可显示它。

  <ol>
    {% for key, files in file %}
        <li>{{file[key]}}</li>
    {% endfor %}
  </ol>