Placing your actual files in an array with different columns that you can sort is probably the best option and also associated with it.
I used asort () "Sort array and maintain index association", I think that best suits your requirements.
if (is_dir($path)) { $FoundFiles = array(); foreach (new DirectoryIterator($path) as $file) { if ($file->isDot()) continue; $fileName = $file->getFilename(); $pieces = explode('.', $fileName); $date = explode('-', $pieces[2]); $filetypes = array( "pdf", "PDF" ); $filetype = pathinfo($file, PATHINFO_EXTENSION); if ( in_array( strtolower( $filetype ), $filetypes )) { $FoundFiles[] = array( "fileName" => $fileName, "date" => $date ); } } }
Before sorting
print_r( $FoundFiles ); Array ( [0] => Array ( [fileName] => readme.pdf [date] => 22/01/23 ) [1] => Array ( [fileName] => zibra.pdf [date] => 22/01/53 ) [2] => Array ( [fileName] => animate.pdf [date] => 22/01/53 ) )
After sorting asort()
asort( $FoundFiles ); print_r( $FoundFiles ); Array ( [2] => Array ( [fileName] => animate.pdf [date] => 22/01/53 ) [0] => Array ( [fileName] => readme.pdf [date] => 22/01/23 ) [1] => Array ( [fileName] => zibra.pdf [date] => 22/01/53 ) )
}
Then to print with HTML after the function finishes - your code did this while the code was in the loop, which meant that you could not sort it after it was already printed:
<ul> <?php foreach( $FoundFiles as $File ): ?> <li>File: <?php echo $File["fileName"] ?> - Date Uploaded: <?php echo $File["date"]; ?></li> <?php endforeach; ?> </ul>
source share