php中数组迭代时的一个小问题.请指导


A minor issue while iteration of array in php.Guidance please

我在一个目录中有几个文件。我想显示所有扩展名为。txt和。jpeg

的文件名
<?php
if ($handle = opendir("/home/work/collections/utils/")) {
    while (false !== ($file = readdir($handle))) {
        if ($file == '.' || $file == '..') {
            continue;
        }
        $actual_file=pathinfo("/etrade/home/collections/utils");
        if (($actual_file["extension"]== "txt") || 
            ($actual_file["extension"]== "jpg") ||      
            ($actual_file["extension"]== "pdf")) {
            //Require changes here.Dont know how to iterate and get the list of files 
            echo "<td>"."'n"." $actual_file['basename']."</a></td>";         
        }
    }
    closedir($handle);
}

请帮助我如何迭代和获得文件列表。例如,我希望所有的文件与jpg扩展名在一个单独的列和pdf文件在一个单独的列(因为我要在一个表中显示)

看看这是不是你想要的(EDITED):

<?php
  $ignoreFiles = array('.','..'); // Items to ignore in the directory
  $allowedExtensions = array('txt','jpg','pdf'); // File extensions to display
  $files = array();
  $max = 0;
  if ($handle = opendir("/home/work/collections/utils/")) {
    while (false !== ($file = readdir($handle))) {
      if (in_array($file, $ignoreFiles)) {
        continue; // Skip items to ignore
      }
      // A simple(ish) way of getting a files extension
      $extension = strtolower(array_pop($exploded = explode('.',$file)));
      if (in_array($extension, $allowedExtensions)) { // Check if file extension is in allow list
        $files[$extension][] = $file; // Create an array of each file type
        if (count($files[$extension]) > $max) $max = count($files[$extension]); // Store the maximum column length
      }
    }
    closedir($handle);
  }
  // Start the table
  echo "<table>'n";
  // Column headers
  echo "  <tr>'n";
  foreach ($files as $extension => $data) {
    echo "    <th>$extension</th>'n";
  }
  echo "  </tr>'n";
  // Table data
  for ($i = 0; $i < $max; $i++) {
    echo "  <tr>'n";
    foreach ($files as $data) {
      if (isset($data[$i])) {
        echo "    <td>$data[$i]</td>'n";
      } else {
        echo "    <td />'n";
      }
    }
    echo "  </tr>'n";
  }
  // End the table
  echo "</table>";

如果你只想显示两个文件列表(不清楚你的问题有什么问题),你不能把文件名存储在数组中吗?

你似乎没有得到文件的详细信息——你得到了/etrade/home/collections/utils的路径信息,但是你从来没有给它添加文件名。

<?php
if ($handle = opendir("/home/work/collections/utils/")) {
    while (false !== ($file = readdir($handle))) {
        if ($file == '.' || $file == '..') {
            continue;
        }
        $actual_file=pathinfo($file);
        switch ($actual_file['extension'])
        {
            case ('jpg'):
                $jpegfiles[] = $actual_file;
                break;
            case ('pdf'):
                $pdffiles[] = $actual_file;
                break;
        }
    }
    closedir($handle);
}

echo "JPG files:"
foreach($jpegfiles as $file)
{
  echo $file['basename'];
}
echo "PDF Files:"
foreach($pdffiles as $file)
{
  echo $file['basename'];
}
?>

显然,你可以更聪明地使用数组,使用多维数组,如果你想的话,可以取消开关。