我之前发过帖子但没有正确地提出问题。因此,一个问题可能看起来像以前的问题,但事实并非如此。请考虑以下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"
实际上,行和列的长度要长得多,但原则保持不变。输出应如下:
然后输出将是一个数组:
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个连续”行连接到另一个,而不是“每隔三行”。谁能告诉我如何完成每第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行,但原理与我猜的相同。
答案 0 :(得分:0)
编辑:您可以做的事情(以及实际上更智能的解决方案,在Java中显示)是:
String[] newarray = new String[147];
for(int i = 0; i < yourarray.length; i++){
newarray[i%147].concat(yourarray[i]);
}
将String []替换为您需要的任何数组类型,并使用您用于连接数组的任何方法替换concat()方法。代码的要点是你需要一些方法将索引为147n + C的原始数组中的元素(对于某些非负整数n,并且某些整数C <147)映射到索引中新数组中的元素C,本质上是模运算的目的。
答案 1 :(得分:0)
你的一般逻辑应该是:
我的PHP太生疏了,无法编写确切的代码来做到这一点,但你所拥有的肯定不会那样做。