Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort files by date latest at top Using RecursiveDirectoryIterator

Tags:

file

php

sorting

Right now by default its display by alphabet i don't want that way. I Want to sort files by using RecursiveDirectoryIterator latest files at top. In descending order.

Also use if condition to compare date & get files from that date

   <?php
    $search_path = 'D:\xampp\htdocs';
    $file_extension = 'php';
    $it = new RecursiveDirectoryIterator("$search_path");
    $display = Array ($file_extension);


    foreach(new RecursiveIteratorIterator($it) as $file) {
        $test = Array();
        $test = explode("/",date("m/d/Y",filemtime($file)));
        $year = $test[2];
        $day = $test[1];
        $month = $test[0];


    if (in_array(strtolower(array_pop(explode('.', $file))), $display))
             if(($year >= 2014) && ($month >= 1) && ($day >= 15 )){
                   echo "<span style='color:red;'>";
                   echo "<b  style='color:green;'>".$day.'-'.$month.'-'.$year. '</b> ' . $file."</span><br>";
             }
        } 

    ?>
like image 649
Rishi Avatar asked Sep 29 '22 12:09

Rishi


1 Answers

I don't know if you can sort thru the DirectoryIterator outright by you could gather the results first, get the time then sort that then present it. Example:

$display = array('php');
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($search_path));
$data = array();
foreach($files as $file) {
    $time = DateTime::createFromFormat('U', filemtime($file->getPathname()));
    // no need to explode the time, just make it a datetime object
    if(in_array($file->getExtension(), $display) && $time > new DateTime('2014-01-15')) { // is PHP and is greater than jan 15 2014
        $data[] = array('filename' => $file->getPathname(), 'time' => $time->getTimestamp()); // push inside
    }

}
usort($data, function($a, $b){ // sort by time latest
    return $b['time'] - $a['time'];
});


foreach ($data as $key => $value) {
    $time = date('Y-m-d', $value['time']);
    echo "
        <span style='color: red;'>
            <b style='color: green;'>$time</b>$value[filename]
        </span>
        <br/>
    ";
}
like image 169
Kevin Avatar answered Oct 02 '22 17:10

Kevin