-1

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

csv 文件 1:member.csv

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

csv 文件 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 来做到这一点 - 没有其他语言。

我会非常感谢一个解决方案。

马特

4

3 回答 3

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

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

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

    // ...
}
于 2012-10-05T17:11:09.177 回答
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);
}
于 2012-10-05T17:19:38.797 回答
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);
}
于 2012-10-05T17:54:54.000 回答