问题
Need to prepare data from .txt file for importing in database via browser. In the example below, there is .txt file (about 40 000 lines). I need to combine every 6 records in one array (first is always timestamp in the example). So, as I understand, some loop is necessary. Tried to find some examples (too easy) but didn't succeed. I appreciate any help you can provide even some link.
.txt example
1=19-10-18 10:02:06
2=+1.313026E+00 l/s
3=+1.671796E-01m/s
4=+1.500691E+02m3
5=+1.501138E+02m3
6=+0.000000E+00m3
1=19-10-18 10:03:06
2=+1.266786E+00 l/s
3=+1.612923E-01m/s
4=+1.501403E+02m3
5=+1.501850E+02m3
6=+0.000000E+00m3
1=19-10-18 10:04:06
2=+1.597391E+00 l/s
3=+2.033861E-01m/s
4=+1.502291E+02m3
5=+1.502738E+02m3
6=+0.000000E+00m3
need to look like:
array(6) {
[0]=>
string(15) "9-10-18 10:02:0"
[1]=>
string(17) "+1.313026E+00 l/s"
[2]=>
string(16) "+1.671796E-01m/s"
[3]=>
string(14) "+1.500691E+02m"
[4]=>
string(14) "+1.501138E+02m"
[5]=>
string(14) "+0.000000E+00m"
}
array(6) {
[0]=>
string(15) "9-10-18 10:03:0"
[1]=>
string(17) "+1.413026E+00 l/s"
[2]=>
string(16) "+1.771796E-01m/s"
[3]=>
string(14) "+1.300691E+02m"
[4]=>
string(14) "+0.501138E+02m"
[5]=>
string(14) "+1.000000E+00m"
}
.
.
.
What i did till now:
$file=fopen("test_file/test.txt","r");
if ($fh = fopen('test.txt', 'r')) {
while (!feof($fh)) {
$line = fgets($fh);
$line=trim($line);
$line=trim($line,"1=");
$line=trim($line,"2=");
$line=trim($line,"3=");
$line=trim($line,"4=");
$line=trim($line,"5=");
$line=trim($line,"6=");
echo"<pre>";
echo $line;
}
fclose($fh);
}
So now result is:
9-10-18,10:02:0
+1.313026E+00 l/s
+1.671796E-01m/s
+1.500691E+02m
+1.501138E+02m
+0.000000E+00m
9-10-18,10:03:0
+1.266786E+00 l/s
+1.612923E-01m/s
+1.501403E+02m
+1.501850E+02m
+0.000000E+00m
Now I need to put in array every 6 records.
回答1:
You can use array_chunk($array, 6);
回答2:
Additionally to chunking, to store it into one array, you can try something like this:
$chunks = array_chunk($array, 6);
$result = array_map(function($chunk) { return array_merge(...$chunk); } , $chunks);
来源:https://stackoverflow.com/questions/58727560/merge-or-combine-n-6-lines-of-text-in-one-array-repeatedly-with-php