Consider 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"
I need to read this CSV and combine every nth, say every third line to each other. Thus, the desired result:
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
)
I need n to be a variable, so it should be easy, for example, to combine every fourth row:
array (
[0] => 1,2,3,4,17,18,19,20,33,34,35,36
[1] => 5,6,7,8,21,22,23,24
[2] => 9,10,11,12,25,26,27,28
)
Now I have this:
$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);
But it does not work as expected, as it outputs
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
)
Do you have a better idea? This mathematical logic always puzzles me !:-)