考虑以下 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行,但我猜原理是一样的。