2012-06-08 20 views
1

我是降價文件的數組是這樣的:排序文件到數組通過在線內容

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

我想由內而外每個人的某行對文件進行排序。

一個實例的文件是:

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

文件的陣列,然後通過排序[號碼到排序]在每個文件中,其可以通過被訪問:

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

最後,我想要從陣列鍵值中去除每個content/.md

+0

哪裏'.md'從何而來? –

回答

2

的代碼在我的腦海裏顯得小了很多,但由此產生的代碼只是三行:)

$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是從哪裏來的,所以你必須讓我知道在那一個:)

-1

嘗試像

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 

你有大部分。只需要放入一個新的數組中的文件和基本名dir和轉關

+0

我不認爲'$ mdfiles [*]'或'$ file_array [*]'是一個有效的語法。 –

+0

這不是,我忘了編輯那部分。謝謝。 – Galen

+0

如果兩個日期值相同,這將不起作用:) –