我之前发表过一篇文章,但没有正确地阐述这个问题。因此,这个问题可能看起来像以前的问题,但不是。考虑以下 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"
实际上,行和列要长得多,但原理保持不变。输出应如下所示:
- 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
)
感谢@nickb,我现在有了:
$path = "data.csv";
$newrow = 1; $row = 1;
if (($handle = fopen($path, "r")) !== FALSE) {
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++;
}
}
print_r($newrows);
但这将“所有 3 个连续的”行相互连接,而不是“每第三行”。谁能告诉我如何完成每第三行的连接?我试过这个,但它以一种奇怪的方式连接起来:
$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
)
edit
实际上,csv 要大得多,我需要将每 147 行连接到前 147 行,但我猜原理是一样的。