Van De Wack Van De Wack - 1 year ago 64
PHP Question

import csv in array's, explode text file by datevalue given or by numrows possible?

Hi i have a csv file which Contains Trace Signals of Vibration Data.
Its Starts with an Iso 8601 Date 2017-01-31T16:16:21.000+01:00
then it have 1024 rows of data(512Hz 2Sec Signal). And then the next Trace signal which starts with the new Date but in the same file -.-.

2017-01-31T16:16:21.000+01:00
0,06;0,03;0,01
0,07;0,03;0,01
0,07;0,03;0,02
.... up to line 1025
2017-01-31T16:24:37.000+01:00
1,72;0,2;-0,9
1,48;0,39;-1,46
1,23;0,58;-1,67
0,99;0,76;-1,81
... up to line 2050


This file can contain much more than 2 traces, how can i pass this in seperated arrays ? i would prefer arrays like :

Array
(
[0] => Array
(
[Time] => 2017-01-31T16:16:21.000
[Data] => array ( [0] => 0,06;0,03;0,01
[1] => 0,07;0,03;0,01 etc..)
)


But I dont know how to loop through the file and explode by the datetime value and also use it. Other way was To read Firstline as Time and next 1024 rows by line and push it but how ?
Regards

Answer Source

You may run into problems as your array gets larger, but this is the approach:

$i = $j = 0;

if($handle = fopen('/path/to/file.csv', 'r')) {
    while(($line = fgets($handle)) !== false) {
        if($i % 1025 === 0) {
            $j++;
            $result[$j]['Time'] = $line;
        } else {
            $result[$j]['Data'][] = $line;
        }
        $i++;
    }
}

Just loop through the file and test if it is the first line or one that is a multiple of 1026. If it is, then you are on a line with the time, if not it is the data.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download