使用PHP在目录中按时间排序文件和文件夹?

时间:2015-04-30 10:06:33

标签: php sorting

我正在尝试使用PHP对目录中的所有文件和文件夹进行排序。

我目前可以获取目录(文件和文件夹)的所有内容并将其显示在我的页面上。

然而,在按上次上传/创建的时间对文件和文件夹进行排序方面,对我来说绝对没有任何作用,并且它将我推向了墙上!

这是我的全部代码:

<?php

$folders = "";

$fileExt = "<i style='font-size:18px;' class='fa fa-folder-open'></i>";

function human_filesize($bytes, $decimals = 2) {
    $size = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
}

$all_doc = "";
$i = 0;
$filesize = "";

$timeFile = "";
if (isset($_GET['dir']) && ($_GET['user'])) {
    $directory = $_GET['dir'];
    $Uid = $_GET['user'];

    //////WE GET THE DIRECTORIES AND FILES HERE///////////////
    $dir = "../" . $directory . "";
    $dirN = substr($dir, strpos($dir, "/") + 1);
    $files = scandir($dir);

    function newest($a, $b) {
        return (filemtime($a) > filemtime($b)) ? -1 : 1;
    }

    usort($files, "newest"); // sort the array by calling newest()

    $TIMEANDATE = date("F d Y h:i A");
    foreach ($files as $file) {
        include "../config/connect.php";
        $result = $db_conx->query("SELECT * FROM processed WHERE fileName='$file' AND userid='$Uid'");
        $row = $result->fetch_array(MYSQLI_BOTH);
        $proces = $row["proces"];
        $invoice = $row["invoice"];

        $date = filemtime('' . $dir . '/' . $file . '');


        if ($file != '.' && $file != '..') {



            $whatIWant = substr(strrchr($file, '.'), 1);



            if ($whatIWant == "jpg" || $whatIWant == "png" || $whatIWant == "gif" || $whatIWant == "JPG" || $whatIWant == "JPEG" || $whatIWant == "jpeg") {
                $fileExt = '<i style="font-size:18px;" class="fa fa-file-image-o"></i>';
            } else {
                $fileExt = "<i style='font-size:18px;' class='fa fa-folder-open'></i>";
            }
            $filesize = human_filesize(filesize('' . $dir . '/' . $file . ''));
            $key = @filemtime('' . $dir . '/' . $file . '');



            if ($whatIWant == "pdf" || $whatIWant == "docx" || $whatIWant == "xlsx" || $whatIWant == "xls" || $whatIWant == "zip" || $whatIWant == "doc" || $whatIWant == "jpg" || $whatIWant == "png" || $whatIWant == "gif" || $whatIWant == "txt" || $whatIWant == "psd") {


                $timeFile = "" . $dir . "/" . $file . "";
                if ($proces == 'yes') {
                    $all_doc .= "<tr>
                        <td><input  type='checkbox'/></td>
                        <td>" . $fileExt . "&nbsp;<a class='defaults'  href='" . $dir . "/" . $file . "'>" . $file . "</a>&nbsp;&nbsp;<a href='move.php?movef=" . $dirN . "/" . $file . "&user=" . $Uid . "'><i title='Move' class='fa fa-refresh'></i></a>&nbsp;&nbsp;
    <a href='folder.php?del=" . $dirN . "/" . $file . "'><i title='Delete' class='fa fa-times'></i>
    </a></td>           


                        <td>" . $invoice . "</td>
                        <td ><a style='color:#0C0;' href='process.php?nopro=" . $file . "&user=" . $Uid . "&loc=" . $dirN . "'>Processed (Click here to un-process)</a></td>
                        <td>" . date('F d Y h:i A', $date) . "</td>
                        <td>" . $filesize . "</td>
                        </td>
                    </tr>";
                } else {
                    $all_doc .= "<tr>
                        <td><input  type='checkbox'/></td>
                        <td>" . $fileExt . "&nbsp;<a class='defaults'  href='" . $dir . "/" . $file . "'>" . $file . "</a>&nbsp;&nbsp;<a href='move.php?movef=" . $dirN . "/" . $file . "&user=" . $Uid . "'><i title='Move' class='fa fa-refresh'></i></a>&nbsp;&nbsp;
    <a href='folder.php?del=" . $dirN . "/" . $file . "'><i title='Delete' class='fa fa-times'></i>
    </a></td>           
                        <td>N/A</td>
                        <td >
                        <a style='color:#F00;' href='process.php?pro=" . $file . "&user=" . $Uid . "&loc=" . $dirN . "&gback=" . $goBack . "'>Not Processed (Click here to Process)</a>
                        <!--<form action='process.php' method='get' >
                        <input type='hidden' name='pro' value='" . $file . "' />                    
                        <input type='hidden' name='user' value='" . $Uid . "' />
                        <input type='hidden' name='loc' value='" . $dirN . "' />
                        <input class='notPro' type='submit' value='Not Processed (Click here to Process)' />
                        </form>-->
                        </td>
                        <!--<td>" . date('F d Y h:i A', $date) . "</td>-->
                        <td>" . date("F d Y H:i:s", filemtime($timeFile)) . "</td>
                        <td>" . $filesize . "</td>

                        </td>
                    </tr>";
                }
            } else {
                $all_doc .= "<tr>
                        <td><input  type='checkbox'/></td>
                        <td>" . $fileExt . "&nbsp;<a class='defaults'  href='folder.php?dir=" . $dirN . "/" . $file . "&user=" . $Uid . "'>" . $file . "</a>&nbsp;&nbsp;<a href='move.php?movef=" . $dirN . "/" . $file . "&user=" . $Uid . "'><i title='Move' class='fa fa-refresh'></i></a>&nbsp;&nbsp;
    <a href='folder.php?del=" . $dirN . "/" . $file . "'><i title='Delete' class='fa fa-times'></i>
    </a></td>

    <td>N/A</td>
                        <td></td>

                        <td>" . date('F d Y h:i A', $date) . "</td>
                        <td>" . $filesize . "</td>
                        </td>
                    </tr>";
            }
            $i++;
        }
    }
}
?>

对于这么多代码感到很抱歉,但我必须向您发送所有代码,以便了解其工作原理!

正如您在我的代码中看到的那样,我正在尝试对内容进行排序:

$dir = "../".$directory."";
$dirN = substr($dir, strpos($dir, "/") + 1);
$files = scandir($dir);

function newest($a, $b)
{
    return (filemtime($a) > filemtime($b)) ? -1 : 1;
}



usort($files, "newest"); // sort the array by calling newest()

但文件和文件夹的输出到处都是。请查看附件图片,了解它目前是如何显示文件和文件夹的:

enter image description here

有人可以就此问题提出建议吗?

任何帮助将不胜感激。

编辑: 此问题不按Date排序。我需要按TIME对文件进行排序。

1 个答案:

答案 0 :(得分:1)

在for循环中,您可以使用

获取文件时间
$date = filemtime('' . $dir . '/' . $file . '');

在此代码中,$file是数组中的文件名。

首先运行的usort函数在$files数组上运行,并使用其裸值。显然,数组不包含目录名。因此,最有可能的是,filemtime函数内对newest的调用将失败并始终返回false。所以返回值永远不会有用。

更好的方法是构造一个包含完整文件路径的数组。然后,该阵列可以更容易地用于排序和进行其他处理。

或者,您可以创建嵌套数组或对象数组,其中每个项目包含文件名,路径,文件日期和其他信息。这样,您可以轻松地分离构造数组,排序和输出信息的过程。排序和输出可以使用对象中的信息,因此您不必多次从磁盘读取文件日期。

<?php
$dir = 'c:\\test\\'; // Or whatever you get your dir from..

$filenames = scandir($dir);
$files = array();

// Build an array with all the meta information you need.
// In this case, I use a nested array (array of arrays),
// but you could as well use objects too.
foreach ($filenames as $filename) {

  $fullpath = $dir . $filename;

  $file = array(
    'filename' => $filename,
    'fullpath' => $fullpath,
    'filedatetime' => filemtime($fullpath)
  );
  $files[] = $file;
}

// Sort the array. Note you can use an inline (anonymous) callback
// function if you have a modern version of PHP.
usort($files, function($file1, $file2) {
  return $file1['filedatetime'] - $file2['filedatetime'];
});

// Output a table of file information by iterating over the enriched 
// files array. In this stage all the info is there, and you don't need 
// to call any file I/O functions.
?>
<table>
  <tr><th>File</th><th>Time</th><th>Path</th></tr>

<?php
foreach ($files as $file) { ?>
  <tr>
    <td><?php echo $file['filename']; ?></td>  
    <td><?php echo date('c', $file['filedatetime']) ?></td>
    <td><?php echo $file['fullpath']; ?></td>
  </tr>
<?php } ?>

</table>

<?php