2013-10-22 85 views
0

我有一個文件,大小約爲10 GB或更多。該文件僅包含從1到10的數字,而不包含其他內容。現在,任務是從文件中讀取數據[數字],然後按照升序或降序對數字進行排序,並使用排序後的數字創建一個新文件。使用PHP處理大文件

有沒有人能幫我解答嗎?

+0

excel文件? csv文件? –

+0

其原始文本文件 –

+0

10GB的原始文本文件?即使操作系統也樂意打開這些尺寸:|你有沒有考慮過**而不是使用PHP來做類似的事情? PHP不是爲這樣的設計而設計的。 – MackieeE

回答

0

我以前有類似的問題。試圖操縱這樣一個大文件最終導致了資源的巨大流失,並且無法應對。我結束了最簡單的解決辦法是嘗試使用所謂的LOAD DATA INFILE

http://dev.mysql.com/doc/refman/5.1/en/load-data.html

,一旦它在你應該能夠操縱數據的快速數據轉存功能將其導入到一個MySQL數據庫。

或者,您也可以逐行讀取文件,並將結果輸出到另一個文件中,並按行排序。不太確定這將如何工作。

您之前是否曾經嘗試過這種嘗試?或者您剛剛採用了這種方法嗎?

0

如果這一切你不需要PHP(如果你手頭有一個Linux maschine):

sort -n file > file_sorted-asc 
sort -nr file > file_sorted-desc 

編輯:好的,這是你的解決方案在PHP(如果你有一臺Linux maschine在手) :

<?php 

// Sort ascending 
`sort -n file > file_sorted-asc`; 

// Sort descending 
`sort -nr file > file_sorted-desc`; 

?> 

:)

+0

'sort'命令使用'/ tmp'目錄來存儲文件,所以沒有足夠的'/ tmp'空間和排序會失敗。您可以使用'-T'開關指定要使用的任意臨時目錄。 – gwillie

+0

我想用PHP解決方案。 –

1

我假設這是somekind的家庭作業和目標,這是更多的數據比你可以在你的RAM持有排序?

既然你只有數字1-10,這不是那麼複雜的任務。只需打開您的輸入文件並計算您擁有的每個具體號碼的次數。之後,您可以構建簡單的循環並將值寫入另一個文件。下面的例子非常自我解釋。

$inFile = '/path/to/input/file'; 
$outFile = '/path/to/output/file'; 
$input = fopen($inFile, 'r'); 
if ($input === false) { 
    throw new Exception('Unable to open: ' . $inFile); 
} 
//$map will be array with size of 10, filled with 0-s 
$map = array_fill(1, 10, 0); 
//Read file line by line and count how many of each specific number you have 
while (!feof($input)) { 
    $int = (int) fgets($input); 
    $map[$int]++; 
} 
fclose($input); 
$output = fopen($outFile, 'w'); 
if ($output === false) { 
    throw new Exception('Unable to open: ' . $outFile); 
} 
/* 
* Reverse array if you need to change direction between 
* ascending and descending order 
*/ 
//$map = array_reverse($map); 
//Write values into your output file 
foreach ($map AS $number => $count) { 
    $string = ((string) $number) . PHP_EOL; 
    for ($i = 0; $i < $count; $i++) { 
     fwrite($output, $string); 
    } 
} 
fclose($output); 

考慮到這樣的事實,即你正在處理大文件,您也應該檢查腳本的執行時間限制你的PHP環境,下面的例子將需要很長的時間10GB +大小的文件,但因爲我沒有」不要在你的問題上看到任何關於執行時間和性能的限制,我假設它是可以的。