有许多的措施,你想要做的任务。显然,第一步是获取文件的内容。您声明您已经能够将文件的内容放入数组中。你可能已经做了这样的事情:
// 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], '"') ]
和/或用trim($elements[1], '"')
替换$elements[1]
。
向我们展示您尝试过的。 – johnluttig 2012-02-22 22:59:39