Consider the following 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"
In reality, the rows and columns are much longer, but the principle stays the same.
I need a way to read the csv file, remove the quotes and concatenate every 3 consecutive rows to each other to format the following output:
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 now have:
$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);
}
What I’m trying to do is create an array “newrows” (see below) in which data is added to the current new row while $row cannot be devided by 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"
)
My code obviously isn’t working, but I am confused as how to proceed. Do you know? Any help is greatly appreciated 🙂
edit I seem to have made a mistake. The output should not be “concatenate every set of 3 rows” but rather “concatenate every third row”, so:
- every 3rd row is concatenated to the previous 3rd one
- row 4 (1 + 3) and 7 (1 + 3 + 3) are concatenated to row 1
- row 5 (2 + 3) and 8 (2 + 3 + 3) are concatenated to row 2
- row 6 (3 + 3) and 9 (3 + 3 + 3) are concatenated to row 3
The output then would be an array:
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 tried this but it concatenates incorrect:
$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
)
P.S. In reality, the csv is much larger and I need every 147th row to be concatenated to the previous 147th row, but the principle is the same I guess.
Your while loop needs some work:
Notable changes:
$rownow starts at 1, so the first three iterations will be mapped to the same entry.$newrows[$newrow] = '';is properly initialized.$row % 3is compared to== 0, which determines if we’re at the end of every third row correctly.$newrows[$newrow]is set to.= implode(",", $data);, which will continually concatenate rows together. Otherwise, only the last iteration would be kept in your original code.