這裏是我採取在此:
- 使用
file
讀取數據文件,產生其中每個元素對應於輸入的線的陣列。
- 使用
array_filter
和trim
作爲過濾器函數,以從該陣列中刪除空行。這有利於trim
返回一個字符串,該字符串從其參數的兩端刪除了空白,如果參數全部爲空白,則保留空字符串。 The empty string converts to boolean false
- 因此使array_filter
忽略全部爲空白的行。
- 使用
array_map
與涉及到調用explode
到每個數組元素(文本行)分成三個部分,並且在返回的這些第二回調。這將產生一個數組,其中每個元素只是一個名稱。
- 使用
array_map
再次strtoupper
作爲回調的所有名稱轉換爲大寫,使「吉姆」和「JIM」會在下一步相同的計數。
- 最後,使用
array_count_values
獲得事件的每個名字的數量。
代碼,採取東西慢慢:
function extract_name($line) {
// The -1 parameter (available as of PHP 5.1.0) makes explode return all elements
// but the last one. We want to do this so that the element we are interested in
// (the second) is actually the last in the returned array, enabling us to pull it
// out with end(). This might seem strange here, but see below.
$parts = explode('||', $line, -1);
return end($parts);
}
$lines = file('data.txt'); // #1
$lines = array_filter($lines, 'trim'); // #2
$names = array_map('extract_name', $lines); // #3
$names = array_map('strtoupper', $names); // #4
$counts = array_count_values($names); // #5
print_r($counts); // to see the results
還有一個原因是我選擇了做這個步驟,每個步驟涉及到上一步的結果的函數調用 - 它實際上可能做到這一點的只有一行:
$counts = array_count_values(
array_map(function($line){return strtoupper(end(explode('||', $line, -1)));},
array_filter(file('data.txt'), 'trim')));
print_r($counts);
See it in action。
我應該指出,這可能不是「最好」的方式來解決在這個意義上的問題,如果你的輸入文件巨大(在幾百萬行的球場),這種方法會消耗大量的因爲它一次讀取內存中的所有輸入。然而,這當然很方便,除非你知道投入會很大,否則讓生活變得更難。
注意:高級PHP開發人員可能已經注意到,我違反了嚴格的標準,將explode
的結果提供給接受其參數引用的函數。這是有效的批評,但在我的辯護中,我試圖儘可能縮短代碼。在生產中,使用$a = explode(...); return $a[1];
確實會更好,但結果不會有差異。
來源
2012-01-16 13:00:13
Jon
顯示到目前爲止,你已經嘗試的代碼,我們會盡力幫助解決問題。但是你必須展示一些努力 - 我們不會爲你寫。這不是這個網站的工作原理。 – 2012-01-16 04:22:43