0

考虑以下 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我好像犯了一个错误。输出不应该是“连接每组 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
)

PS实际上,csv要大得多,我需要将每147行连接到前147行,但我猜原理是一样的。

4

1 回答 1

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);,它将不断地将行连接在一起。否则,只有最后一次迭代会保留在您的原始代码中。
于 2012-07-14T21:51:15.323 回答