如何将CSV行连接成新行?

时间:2012-07-14 21:39:32

标签: php csv

考虑以下data.csv:

 "1", "2", "3", "4"
 "5", "6", "7", "8"
 "9","10","11","12"
"13","14","15","16"
"17","18","19","20"
"21","22","23","24"
"25","26","27","28"
"29","30","31","32"
"33","34","35","36"

实际上,行和列的长度要长得多,但原则保持不变。

我需要一种方法来读取csv文件,删除引号并将每3个连续的行连接起来以格式化以下输出:

1,2,3,4,5,6,7,8,9,10,11,12
13,14,15,16,17,18,19,20,21,22,23,24
25,26,27,28,29,30,31,32,33,34,35,36

我现在有:

$path = "data.csv";
$row = 0;
$newrow = 0;
$newrows = array();
if (($handle = fopen($path, "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $newrows[$newrow] = implode("," $data);
    if ($row % 3) $newrow++;
    $row++;
  }
  fclose($handle);
}

我要做的是创建一个阵列" newrows" (见下文)其中数据被添加到当前新行,而$ row不能被3

分开
$newrows = array (
  [0] = "1,2,3,4,5,6,7,8,9,10,11,12",
  [1] = "13,14,15,16,17,18,19,20,21,22,23,24",
  [2] = "25,26,27,28,29,30,31,32,33,34,35,36"
)

我的代码显然不起作用,但我很困惑如何继续。你知道吗?非常感谢任何帮助: - )

edit我似乎犯了一个错误。输出不应该是#34;连接每组3行"而是#34;连接第三行",所以:

  • 每第3行连接到前一个第3行
  • 第4行(1 + 3)和第7行(1 + 3 + 3)连接到第1行
  • 第5行(2 + 3)和第8行(2 + 3 + 3)连接到第2行
  • 第6行(3 + 3)和第9行(3 + 3 + 3)连接到第3行

然后输出将是一个数组:

array (
  [0] => 1,2,3,4,13,14,15,16,25,26,27,28
  [1] => 5,6,7,8,17,18,19,20,29,30,31,32
  [2] => 9,10,11,12,21,22,23,24,33,34,35,36
)

我尝试了这个,但它连接不正确:

$path = "data.csv";
$row = 1;
if (($handle = fopen($path, "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    for ($i = 1; $i <= 3; $i++) {
      if ($row % $i == 0) $newrows[$i] .= implode(",", $data);
    }
    $row++;
  }
}

print_r($newrows);

Array (
  [1] => 1,2,3,45,6,7,89,10,11,1213,14,15,1617,18,19,2021,22,23,2425,26,27,2829,30,31,3233,34,35,36
  [2] => 5,6,7,813,14,15,1621,22,23,2429,30,31,32
  [3] => 9,10,11,1221,22,23,2433,34,35,36
)

P.S。实际上,csv要大得多,我需要将每第147行连接到前一个第147行,但原理与我猜的相同。

1 个答案:

答案 0 :(得分:4)

你的while循环需要一些工作:

$newrow = 0; $row = 1;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if( !isset( $newrows[$newrow])) $newrows[$newrow] = '';
    $newrows[$newrow] .= implode(",", $data);
    if ($row % 3 == 0) {
        $newrow++;
    } else {
        $newrows[$newrow] .= ', ';
    }
    $row++;
}

值得注意的变化:

  • $row现在从1开始,因此前三次迭代将映射到同一条目。
  • $newrows[$newrow] = '';已正确初始化。
  • $row % 3== 0进行比较,后者确定我们是否正确地位于每个第三行的末尾。
  • $newrows[$newrow]设置为.= implode(",", $data);,它会不断地将行连接在一起。否则,只有最后一次迭代将保留在原始代码中。