按行内容将文件分类到数组中


Sort Files into Array by Line Content

我有这样的降价文件数组:

$mdfiles = glob("content/*.txt", GLOB_NOSORT);

我想按每个文件内部的某一行对文件进行排序。

示例文件为:

File
====
line-one:
date: [number-to-sort]

然后,每个文件中的文件数组按 [number-to-sort] 排序,可通过以下方式访问:

$file_array = file($mdfiles[*], FILE_IGNORE_NEW_LINES)
substr($file_array[*], 6);

最后,我想从数组键值中删除每个content/.md

代码在我脑海中看起来要小得多,但生成的代码只有三行:)

$files = glob('content/*.txt', GLOB_NOSORT);
// sort the file array by date; see below
usort($files, 'by_file_date');
// strip the filename
$files = array_map('strip_filename', $files);

'by_file_date'函数稍后声明,基本上在内部使用 get_date 函数来执行从文件中"拉取"日期。我根据您显示的表单使用了preg_match来查找日期值;我假设date是一个整数(即数字序列)。如果没有,请告诉我。

// pull date value from the file
// @todo this function can be optimized by keeping a static array of
//   files that have already been processed
function get_date($f)
{
    // match the date portion; i'm assuming it's an integer number
    if (preg_match('/^date:'s*('d+)/', file_get_contents($f), $matches)) {
        return (int)$matches[1];
    }
    return 0;
}
function by_file_date($a, $b)
{
    // sort by date ASC
    return get_date($a) - get_date($b);
}

最后,您需要去除文件名;假设您只需要文件名而不是目录:

function strip_filename($f)
{
    // strip the directory portion
    return basename($f);
}

不知道.md是从哪里来的,所以你必须让我知道那个:)

尝试类似

foreach( $mdfiles as $file ) {
    $file_array = file($file, FILE_IGNORE_NEW_LINES);
    $order = substr( $file_array[0], 6 ); // get 6th character till the end of the first line
    $files[$order] = basename( $file, '.md' );
}
ksort($files); // might need this depending on how youre using the array

你拥有大部分。 只需要将文件放在一个新数组中,并对目录和分机进行基本命名