I'm currently echoing all the names of the files in a given directory with php.
The files have a naming convention:
Year person was born _ last name first name
eg.
1980_doejohn.php
1980_elfsarah.php
1981_fitzjack.php
1983_guptasiva.php
I need to rsort them first by year, and sort within each year so the output should be:
1983_guptasiva.php
1981_fitzjack.php
1980_doejohn.php
1980_elfsarah.php
My current (non sorting) code is:
<?php
$filename = glob("about/*.php");
rsort($filename);
foreach ($filename as $filenamein) {
echo ($filenamein) . "<br>";
}
?>
How should I modify it to make it sort the way I want it to? Please provide the entire code suggestion including the
You'll need to write your own comparison function for this and use usort. This works:
$filename = glob("about/*.php");
usort($filename, 'filename_cmp');
foreach($filename as $filenamein)
echo ($filenamein) . '<br />';
function filename_cmp($a, $b){
$diff = (int)substr($b, 0, 4) - (int)substr($a, 0, 4);
if($diff !== 0)
return $diff;
return strcmp(substr($a,5), substr($b,5));
}