开发者

How do I sort and rsort files based on two parts of the filename in PHP?

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_gup开发者_Python百科tasiva.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));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜