按创建日期排序glob()

时间:2014-01-05 04:38:58

标签: php

我正在使用

foreach(glob("config/pages/*.php") as $page){

获取config/pages/目录中所有文件的列表我是否可以先显示最旧的文件,最新的文件最后显示?

我想要制作出所有这些的导航菜单。我的完整源代码如下,但我需要先显示最旧的文件,也许我可以为每个文件添加一个变量,如:`$ order = 1;'数字是列表中的顺序?

所以例如对于页面home.php$order将等于0并且about.php将等于1.然后以某种方式按照从0开始的顺序排序?

<ul class="sidebar-nav">

<li class="sidebar-brand"><a href="#"><?php echo $config['site_title']; ?></a></li>

<?php

    $files = glob("config/pages/*.php");

    $files = array_combine(array_map("filemtime", $files), $files);

    ksort($files);


    foreach($files as $page){

        // Remove the conifg/pages/ from the string
        $strip1 = str_replace('config/pages/', '', $page);

        // Remove the .php from the string
        $strip2 = str_replace('.php', '', $strip1);

        // Uppercase the first letter in the string
        $capit = ucfirst($strip2);

        // Re-define the string as the display title
        $title = $capit;

        // Remove the .php and replace it with .html
        $html = str_replace('.php', '.html', $strip1);

        // Re-define the string for the link url
        $link = $html;

        // Display the end string with html elements to user
        echo "<li><a href='".$link."'>".$title."</a></li>";
    }

?>

2 个答案:

答案 0 :(得分:5)

试试这段代码。我在我的项目中使用过。请检查。

$myarray = glob("config/pages/*.php");
usort($myarray, function($a,$b){
  return filemtime($a) - filemtime($b);
});

答案 1 :(得分:0)

我分三步完成。先阅读你的清单。然后创建一个具有文件修改时间的关联数组,然后按升序排序。

$files = glob("config/pages/*.php");
$files = array_combine(array_map("filemtime", $files), $files);
ksort($files);

因此,最旧的文件将位于列表顶部。

相关问题