你有什么试过?
你可以尝试这样的事:
$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