0

我需要我的脚本按日期对 .txt 文件进行排序。这就像一个简单的新闻脚本,我所做的是添加名为的 .txt 文件:

[23.7.13] 新酷标题 [24.7.13] 建议和提示

并回显内容,已经准备好包括回显部分在内的所有内容,但是它不会按第一个日期对它们进行排序..我该怎么做?

<?
    if( $handle = opendir( 'includes/news' )) 
    {
        while( $file = readdir( $handle )) 
        {
            if( strstr( $file, "txt" ) )
            {
                $addr = strtr($file, array('.txt' => ''));
                echo '<h1><a href="?module=news&read=' . $addr . '">&raquo;' .
                    $addr . "</a></h1>";
            }
         }
        closedir($handle);
    }
}
?>
4

1 回答 1

0
$files = array();
$dir = new DirectoryIterator('includes/news');
foreach ($dir as $fileinfo) {     
    $files[$fileinfo->getMTime()] = $fileinfo->getFilename();
}

ksort($files);

编辑:(试试这个);

<?
$dir = new DirectoryIterator('includes/news');
//$dir = new DirectoryIterator('.');
$num = 0;
foreach ($dir as $fileinfo) {     
$name = $fileinfo->getFilename();
preg_match_all('/\[(.*?)\]/',$string, $matches); 
//preg_match_all('/\-(.*?)\-/',$name, $matches);
if(!empty($matches[1])) {
    //create timestamp (to use for key)
    $timestamp = strtotime($matches[1][0]);
    //use this as array key (to order by with ksort()
    $files[$timestamp]['name'] = $name;
}
}

//sort 
ksort($files);

//get the key back to the normal date 
foreach($files as $key=>$value) {
    $sorted_files[date('d.m.Y',$key)] = $value; 
}

var_dump($files);
?>
于 2013-07-25T08:30:54.267 回答