考虑 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 并每隔 n 次连接一次,比如每隔 3 行连接一次。所以想要的输出是:
array (
[0] => 1,2,3,4,13,14,15,16,25,26,27,28 // row 1, 4 and 7
[1] => 5,6,7,8,17,18,19,20,29,30,31,32 // row 2, 5 and 8
[2] => 9,10,11,12,21,22,23,24,33,34,35,36 // row 3, 6 and 9
)
我需要 n 是可变的,所以它应该很容易,例如,连接每 4 行:
array (
[0] => 1,2,3,4,17,18,19,20,33,34,35,36 // row 1, 5 and 9
[1] => 5,6,7,8,21,22,23,24 // row 2, 6
[2] => 9,10,11,12,25,26,27,28 // row 3, 7
)
我现在有这个:
$path = "data.csv";
$row = 1;
if (($handle = fopen($path, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
for ($i = 1; $i <= 3; $i++) { // concatenate every 3rd row
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
)
你有更好的主意吗?这个数理逻辑一直让我不解!:-)