你有什麼試過?
你可以嘗試這樣的事:
$handle = fopen('file.txt', 'r');
$output = [];
$currentCountryCode = '';
$currentSet = [];
if ($handle) {
while (($line = fgets($handle, 4096)) !== false) {
$line = trim($line);
if (preg_match('/^([a-zA-Z,\'\"]*)\s([A-Z]{2})$/', $line, $matches)) {
// var_dump($matches);exit;
// This is a country line, we need to reset the current set
$currentSet = [];
$currentCountryCode = $matches[2];
} else if (preg_match('/^([a-z\-0-9]*)$/i', $line, $matches)) {
// If the current set is empty, add the current country code
if (count($currentSet) === 0) {
$currentSet[] = $currentCountryCode;
}
// This is a region line
$currentSet[] = $line;
} else if (preg_match('/^([0-9]{2}\sUsers)$/', $line, $matches)) {
// This is a users line
$currentSet[] = $line;
// We need to add the set to the output array
$output[] = $currentSet;
// And reset it
$currentSet = [];
} else {
$error = 'Could not this match line! Need to update the regexes!' . PHP_EOL . var_export(['line' => $line], true);
throw new Exception($error);
}
}
fclose($handle);
}
var_export($output);
測試中PHP7.0.20
| => php test.php
array (
0 =>
array (
0 => 'AT',
1 => 'Vienna-S03-I01',
2 => '30 Users',
),
1 =>
array (
0 => 'AT',
1 => 'Vienna-S03-I02',
2 => '31 Users',
),
2 =>
array (
0 => 'AU',
1 => 'Sydney-S01-I01',
2 => '49 Users',
),
3 =>
array (
0 => 'AU',
1 => 'Sydney-S01-I02',
2 => '46 Users',
),
4 =>
array (
0 => 'BE',
1 => 'Brussels-S01-I01',
2 => '39 Users',
),
5 =>
array (
0 => 'BE',
1 => 'Brussels-S01-I02',
2 => '32 Users',
),
)
您可能需要調整正則表達式,因爲我還沒有實際測試過這個腳本。此外,只有當您的其他數據的結構與您提供的第一行完全一致時,此功能纔有效。祝你好運!
感謝您的幫助。我非常喜歡這個主意。我測試了它,它正在處理的例外是它不添加國家代碼。這就是我得到:'0 => 0 =>維也納-S03-I01 1 => 30個用戶 1 => 0 =>維也納-S03-I02 1 => 31個用戶 2 => 0 =>悉尼-S01-I01 1 => 49個用戶 3 => 0 =>悉尼-S01-I02 1 => 46個用戶 4 => 0 =>布魯塞爾-S01-I01 1 => 39用戶 5 => 0 => Brussels-S01-I02 1 => 32用戶'雖然 – khofm
不會觸發錯誤信息它看起來像'if(count($ currentSet)=== 0){'永遠不會因爲該集合從不爲空而被觸發。 – khofm
不要試圖表達自己的意思,但我想你還應該注意上面的其他答案,因爲可以根據OP的要求命名和進一步處理陣列。 – msalperen