Van De Wack Van De Wack - 1 year ago 57
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 -.-.

.... up to line 1025
... 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 :

[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 ?

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) {
            $result[$j]['Time'] = $line;
        } else {
            $result[$j]['Data'][] = $line;

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