我有一个制表符分隔的文本文件,如下所示:
"abcdef1" "AB"
"abcdef1" "CD"
"ghijkl3" "AA"
"ghijkl3" "BB"
"ghijkl3" "CC"
对于每个公共ID(例如abcdef1),我需要将两位数代码连接成一个多值。所以,最终应该看起来像:
"abcdef1" "AB,CD"
"ghijk13", "AA,BB,CC"
我不需要创建一个新的输出txt文件,但是如果我可以获得一个很棒的数组中的最终值。我只是一个星期的PHP,因此寻求帮助。我能够将输入txt文件中的值转换为数组,但是进一步处理数组以获取公共ID并获取2位数代码并连接是我正在努力的事情。非常感谢任何帮助
答案 0 :(得分:4)
怎么样:
$values = array();
$handle = fopen($file, 'r');
// get the line as an array of fields
while (($row = fgetcsv($handle, 1000, "\t")) !== false) {
// we haven't seen this ID yet
if (!isset($values[$row[0]])) {
$values[$row[0]] = array();
}
// add the code to the ID's list of codes
$values[$row[0]][] = $row[1];
}
$values
将类似于:
Array
(
[abcdef1] => Array
(
[0] => AB
[1] => CD
)
[ghijkl3] => Array
(
[0] => AA
[1] => BB
[2] => CC
)
)
答案 1 :(得分:0)
您要执行的任务有许多步骤。显然,第一步是获取文件的内容。您声明您已经能够将文件的内容放入数组中。你可能做过这样的事情:
// Assuming that $pathToFile has the correct path to your data file
$entireFile = file_get_contents( $pathToFile );
$lines = explode( '\n', $entireFile ); // Replace '\n' with '\r\n' if on Windows
如何将线条放入阵列并不重要。从现在开始,我假设您已设法填充$lines
数组。一旦你有了这个,剩下的就相当简单了:
// Create an empty array to store the results in
$results = array();
foreach( $lines as $line ){
// Split the line apart at the tab character
$elements = explode( "\t", $line );
// Check to see if this ID has been seen
if( array_key_exists( $elements[0], $results ){
// If so, append this code to the existing codes for this ID (along with a comma)
$results[ $elements[0] ] .= ',' . $elements[1];
} else {
// If not, this is the first time we've seen this ID, start collecting codes
$results[ $elements[0] ] = $elements[1];
}
}
// Now $results has the array you are hoping for
对此有一些变化 - 例如,如果您想要删除每个ID周围或每个代码周围的引号,您可以将$results[ $elements[0] ]
替换为$results[ trim( $elements[0], '"' ) ]
和/或替换$elements[1]
与trim( $elements[1], '"' )
。