2012-02-22 99 views
3

我有个制表符分隔的文本文件是这样的:多维阵列处理

"abcdef1" "AB"  
"abcdef1" "CD"  
"ghijkl3" "AA"  
"ghijkl3" "BB"  
"ghijkl3" "CC"  

对于每一个公共ID(例如abcdef1),我需要采取两个数字代码的串连成一个多值。所以,最终它应该看起来像:

"abcdef1" "AB,CD" 

"ghijk13", "AA,BB,CC" 

我不需要创建一个新的输出txt文件,但如果我可以在阵列中获得最终值,这将是巨大的。我只是一个星期到PHP,因此寻找这方面的帮助。我能够从输入txt文件中获取值到数组中,但是进一步处理数组以获得公共ID并采用2位数代码和连接是我正在努力的。任何帮助是极大的赞赏

+3

向我们展示您尝试过的。 – johnluttig 2012-02-22 22:59:39

回答

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 
     ) 

) 
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], '"') ]和/或用trim($elements[1], '"')替换$elements[1]

+0

非常感谢@cbuckley和@Jazz!我的初始阵列与Jazz提到的基本相同,但我不知何故错过了array_key_exists(),并尝试使用临时数组来实现它,并且无法使用它。再次感谢。 – rb022012 2012-02-23 16:29:21