读取php中两个csv文件的内容,并根据关键字段将它们合并到第三个文件中

时间:2012-10-05 17:06:23

标签: php csv merge

我在网上搜索并查看了现有的答案,但无法找到解决方案。我想用php来完成以下任务。这是我的文件:

csv file 1:member.csv

member1|john|smith|2009
member2|adam|jones|2007
member3|susie|rose|2002

csv file 2:classes.csv

member1|massage|swimming|weights
member2|gym|track|pilates
member3|yoga|running|stretches

我想输出一个名为file3.csv的第三个文件,它根据作为成员编号的关键字段将上述两个文件合并在一起。输出应该是这样的:

member1|john|smith|2009|massage|swimming|weights         
member2|adam|jones|2007|gym|track|pilates    
member3|susie|rose|2002|yoga|running|stretches

分隔符是一个条形字符。我想这只是使用PHP - 没有其他语言。

我会非常感谢解决方案。

马特

3 个答案:

答案 0 :(得分:1)

  1. 使用键读取两个文件并将数据存储到数组:member1,...

  2. 循环写一个新文件行:

  3. foreach ($firstArray as $key => $value1) {
        $value2 = $secondArray[$key];
    
        // ...
    }
    

答案 1 :(得分:0)

<?php
$data = array();
if (($handle = fopen('file1.csv', 'r')) !== FALSE) {
    while (($line = fgetcsv($handle, 0, '|')) !== FALSE) {
        $memberId = $line[0];
        unset($line[0]);
        $data[$memberId] = $line;
    }
    fclose($handle);
}
if (($handle = fopen('file2.csv', 'r')) !== FALSE) {
    while (($line = fgetcsv($handle, 0, '|')) !== FALSE) {
        $memberId = $line[0];
        unset($line[0]);
        $data[$memberId] = array_merge($data[$memberId], $line);
    }
    fclose($handle);
}
ksort($data);       // not needed, but puts records in order by member
if (($handle = fopen('file3.csv', 'w')) !== FALSE) {
    foreach($data as $key => $value) {
        fwrite($handle, "$key|" . implode('|', $value) . "\n");
    }
    fclose($handle);
}

答案 2 :(得分:0)

试试这个。这是未经测试的。

$arr_one = array();
if (($fp = fopen("member.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
    $arr_one[$data[0]] = $data;
  }
  fclose($fp);
}
$arr_two = array();
if (($fp = fopen("classes.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
    $arr_two[$data[0]] = $data;
  }
  fclose($fp);
}
$classes_field_count = sizeof(current($arr_two));
$members = array_keys($arr_one);
foreach ($members as $key) {
  if (!isset($arr_two[$key])) {
    $arr_two[$key] = range(0, ($classes_field_count - 1));
  }
  unset($arr_two[$key][0]);
  $result_arr[$key] = array_merge($arr_one[$key], $arr_two[$key]);      
}
if (($fp = fopen("file3.csv", "w")) !== FALSE) {
  foreach ($result_arr as $fields) {
    fputcsv($fp, $fields, '|');
  }
  fclose($fp);
}